除了将所有内容添加到 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?

查看:24
本文介绍了除了将所有内容添加到 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 允许使用非常复杂的规则来扫描服务,因此如果您的服务确实遵循某种模式,您可能能够为此制定规则.

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天全站免登陆