【发布时间】:2016-04-16 08:51:49
【问题描述】:
在 Autofac 中,您可以使用 RegisterAssemblyTypes 注册您的依赖项
所以你将能够做这样的事情,有没有办法在DI for .net Core 的构建中做类似的事情
builder.RegisterAssemblyTypes(Assembly.Load("SomeProject.Data"))
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
这就是我要注册的内容
LeadService.cs
public class LeadService : ILeadService
{
private readonly ILeadTransDetailRepository _leadTransDetailRepository;
public LeadService(ILeadTransDetailRepository leadTransDetailRepository)
{
_leadTransDetailRepository = leadTransDetailRepository;
}
}
LeadTransDetailRepository.cs
public class LeadTransDetailRepository : RepositoryBase<LeadTransDetail>,
ILeadTransDetailRepository
{
public LeadTransDetailRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory) { }
}
public interface ILeadTransDetailRepository : IRepository<LeadTransDetail> { }
这就是我当时尝试注册的方式,但我不知道如何注册存储库 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"]));
}
【问题讨论】:
-
自动布线代码很容易自己实现。所需要的只是一些反射代码和您自己的扩展方法。 Autofac 是开源的,你可以看看你感兴趣的方法是如何实现的,然后自己添加到 MVC Core 中。
标签: c# dependency-injection asp.net-core