[英]cannot create scope of services in repository constructor asp.net core
[英]asp.net core, Ef core : Dynamically map repository and services in run time
我一直在将我的存储库类映射到它的接口,同样也用于服务。 在这里我可以手动注册它们。 但我希望我的代码在运行时动态映射这些代码,这样我就不必在每次创建新的存储库或服务时手动注册它们。 我怎样才能做到这一点?
这是我的代码:
public void RegisterDependencies(IServiceCollection services, IConectionSetting connectionSetting)
{
services.AddDbContext<QuantumDbContext>(options => options.UseSqlServer(connectionSetting.Get()));
//services.AddDbContext<TestDbContext>(options => options.UseSqlServer(databaseFactory.ConnectionString));
services.AddTransient<IDatabaseFactory, DatabaseFactory>();
services.AddTransient<IDbContext, TestDbContext>();
services.AddTransient<IDbContext, QuantumDbContext>();
services.AddTransient<IUnitOfWorkManager, UnitOfWorkManager>();
services.AddTransient<IRepository<CodeTable>, Repository<CodeTable>>();
services.AddTransient<IRepository<Country>, Repository<Country>>();
services.AddTransient<IRepository<State>, Repository<State>>();
services.AddTransient<IRepository<City>, Repository<City>>();
services.AddTransient<ICodeTableService, CodeTableService>();
services.AddTransient<ICountryService, CountryService>();
}
让我把你的问题分成两个问题:
1-如何使用内置DI库在asp.net核心中注册和解析泛型类型?
(参见vNext依赖注入通用接口 )
services.AddTransient<IRepository<CodeTable>, Repository<CodeTable>>();
services.AddTransient<IRepository<Country>, Repository<Country>>();
services.AddTransient<IRepository<State>, Repository<State>>();
你可以简单地注册这样的存储库:
services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
2-如何在内置DI库的asp.net核心中实现批量注册(基于约定)? (参见ASP.NET 5 / MVC 6中基于约定的绑定 )
services.AddTransient<ICodeTableService, CodeTableService>();
services.AddTransient<ICountryService, CountryService>();
我使用以下代码来实现批量注册,它按预期工作,但我不确定它是否是好方法(在此实现中可能有错误的代码):
// i assume your service interfaces inherit from IService
Assembly ass = typeof(ICodeTableService).GetTypeInfo().Assembly;
// get all concrete types which implements IService
var allServices = ass.GetTypes().Where(t =>
t.GetTypeInfo().IsClass &&
!t.GetTypeInfo().IsAbstract &&
typeof(IService).IsAssignableFrom(t));
foreach (var type in allServices)
{
var allInterfaces = type.GetInterfaces();
var mainInterfaces = allInterfaces.Except
(allInterfaces.SelectMany(t => t.GetInterfaces()));
foreach(var itype in mainInterfaces)
{
if (allServices.Any(x => !x.Equals(type) && itype.IsAssignableFrom(x)))
{
throw new Exception("The " + itype.Name + " type has more than one implementations, please change your filter");
}
services.AddTransient(itype, type);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.