gpt4 book ai didi

c# - asp.net核心,EF核心: Dynamically map repository and services in run time

转载 作者:太空狗 更新时间:2023-10-29 23:37:13 29 4
gpt4 key购买 nike

我一直在将我的存储库类映射到它的接口(interface),服务也是如此。在这里我可以手动注册它们。但我希望我的代码在运行时动态映射这些,这样我就不必在每次创建新存储库或服务时都手动注册它们。我怎样才能做到这一点?

这是我的代码:

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 core 中注册和解析泛型?

(参见 vNext Dependency Injection Generic Interface)

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 core中实现批量注册(基于约定)? (参见 Convention based binding in 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);
}
}

关于c# - asp.net核心,EF核心: Dynamically map repository and services in run time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37988238/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com