ASP.NET Core 中的依赖注入

R4n*_*c1d 5 c# dependency-injection asp.net-core

在 Autofac 中,您可以使用 RegisterAssemblyTypes 注册您的依赖项,这样您就可以执行这样的操作,有没有办法在构建中执行类似DI的操作.net Core

builder.RegisterAssemblyTypes(Assembly.Load("SomeProject.Data"))
    .Where(t => t.Name.EndsWith("Repository"))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)

这就是我要注册的内容

LeadService.cs

public class LeadService : ILeadService
{
    private readonly ILeadTransDetailRepository _leadTransDetailRepository;

    public LeadService(ILeadTransDetailRepository leadTransDetailRepository)
    {
        _leadTransDetailRepository = leadTransDetailRepository;
    }
}
Run Code Online (Sandbox Code Playgroud)

LeadTransDetailRepository.cs

public class LeadTransDetailRepository : RepositoryBase<LeadTransDetail>, 
    ILeadTransDetailRepository
{
    public LeadTransDetailRepository(IDatabaseFactory databaseFactory) 
        : base(databaseFactory) { }
}

public interface ILeadTransDetailRepository : IRepository<LeadTransDetail> { }
Run Code Online (Sandbox Code Playgroud)

这就是我当时尝试注册的方式,但我无法弄清楚如何注册存储库 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddTransient<ILeadService, LeadService>();

    //not sure how to register the repositories
    services.Add(new ServiceDescriptor(typeof(ILeadTransDetailRepository),
        typeof(IRepository<>), ServiceLifetime.Transient));

    services.Add(new ServiceDescriptor(typeof(IDatabaseFactory),
        typeof(DatabaseFactory), ServiceLifetime.Transient));
    services.AddTransient<DbContext>(_ => new DataContext(
        this.Configuration["Data:DefaultConnection:ConnectionString"]));
}
Run Code Online (Sandbox Code Playgroud)

Tse*_*eng 4

ASP.NET Core 依赖注入/IoC 容器没有开箱即用的方法来实现这一点,但它是“设计使然”的。

ASP.NET IoC Container/DI 旨在成为添加 DI 功能的简单方法,并作为构建到 ASP.NET Core 应用程序中的其他 IoC 容器框架的基础。

话虽这么说,它支持简单的场景(注册,尝试使用第一个构造函数和大多数参数来满足依赖项和作用域依赖项),但它缺乏自动注册或装饰器支持等高级场景。

对于此功能,您必须使用第 3 方库和/或第 3 方 IoC 容器(AutoFac、StructureMap 等)。它们仍然可以插入IServiceCollection您之前的注册仍然有效,但您还可以获得其他功能。