除了将所有内容添加到Startup类之外,还有一种健壮的方法来在ASP.NET Core 3.1中注册依赖项吗? [英] Is there a robust way to register dependencies in ASP.NET Core 3.1 beside adding everything into Startup class?

查看:82
本文介绍了除了将所有内容添加到Startup类之外,还有一种健壮的方法来在ASP.NET Core 3.1中注册依赖项吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Core 3.1项目.通常,我使用 Startup.cs 类中的 ConfigureServices()方法注册任何依赖项.

I have an ASP.NET Core 3.1 project. Typically, I register any dependency using the ConfigureServices() method in the Startup.cs class.

但是,我发现自己不得不注册许多依赖项,并且 ConfigureServices()看起来很大!我知道我可以创建一个静态方法的扩展方法,并从ConfigureService()类中调用它,但是想知道是否有更好的方法.

But, I find myself having to register lots of dependencies and the ConfigureServices() looks huge! I know I can probably create an extension method of a static method and call it from the ConfigureService()` class, but wondering if there is a better way.

如果有一种方法可以在IoC容器中注册依赖项,而不必每次都这样定义它们

If there a way to register dependencies in the IoC container without having to define them one at a time like this

services.AddScoped<Interface, Class>();
.... 200 lines later
services.AddScoped<ISettings, Settings>()

推荐答案

将相关的依赖项分组到自定义扩展方法中是一种非常常见的方法.ASP.NET Core已经为许多内部服务执行了此操作,您可以轻松地在此基础上进行扩展,并根据应用程序的需要设置它们.例如,设置身份验证和授权:

Grouping related dependencies into custom extension methods is a very common way to do this. ASP.NET Core already does this for many of the internal services, and you can easily expand on top of that and set them up the way you need for your application. For example to set up authentication and authorization:

public IServiceCollection AddSecurity(this IServiceCollection services)
{
    services.AddAuthentication()
        .AddCookie();

    service.AddAuthorization(options =>
    {
        options.DefaultPolicy = …;
    });

    return services;
}

您可以对特定于应用程序的服务执行相同的操作,并在单独的扩展方法中对它们进行逻辑分组.

You can do the same for your application-specific services and group them logically in separate extension methods.

如果您有很多非常相似的服务注册,则还可以采用基于约定的注册,例如使用 Scrutor .例如,这会将某个名称空间内的所有服务注册为它们各自接口的临时服务:

If you have a lot of service registrations that are very similar, you can also employ a convention-based registration e.g. using Scrutor. For example, this registers all services within a certain namespace as transient for their respective interface:

services.Scan(scan => scan
    .FromAssemblyOf<Startup>()
        .AddClasses(c => c.InNamespaces("MyApp.Services"))
            .AsImplementedInterfaces()
            .WithTransientLifetime()
);

Scrutor允许使用非常复杂的规则来扫描服务,因此,如果您的服务确实遵循 some 模式,则您可能会为此制定一个规则.

Scrutor allows for very complex rules to scan for services, so if your services do follow some pattern, you will likely be able to come up with a rule for that.

这篇关于除了将所有内容添加到Startup类之外,还有一种健壮的方法来在ASP.NET Core 3.1中注册依赖项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆