.Net Core + DI:Class 集中接口
.Net Core + DI: Class To Centralize Interfaces
我是 .Net Core 和 Microsoft 依赖注入的新手,我想做的是类似于“.ToFactory()”(来自 ninject),我可以创建一个 class 包含我所有的接口服务,避免在我的控制器上使用很多 IMyClassService。
在 .Net Framework + Ninject 中,我曾经这样做:
Ninject模块
Bind< IAppServiceFactory >().ToFactory();
IAppServiceFactory class
public interface IAppServiceFactory
{
IAccessAgreementAppService AccessAgreement { get; }
IAccessAgreementUserAppService AccessAgreementUser { get; }
...
控制器
private readonly IMapper _mapper;
private readonly IAppServiceFactory _appServiceFactory;
public MyController(IMapper mapper,
IAppServiceFactory appServiceFactory)
{
_mapper = mapper;
_appServiceFactory = appServiceFactory;
}
public ActionResult Index()
{
var all = _appServiceFactory.AccessAgreementUser.GetAll();
}
主要原因是有一个更干净的控制器,而不是
private readonly IAccessAgreementAppService _accessAgreementAppService;
private readonly IAccessAgreementUserAppService _accessAgreementUserAppService;
...
public MyController(IAccessAgreementAppService accessAgreementAppService,
IAccessAgreementUserAppService accessAgreementUserAppService,
...
您可以申请 IServiceProvider
并自行获取服务。
public MyController(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IAccessAgreementAppService();
var all = service.GetAll();
}
}
我是 .Net Core 和 Microsoft 依赖注入的新手,我想做的是类似于“.ToFactory()”(来自 ninject),我可以创建一个 class 包含我所有的接口服务,避免在我的控制器上使用很多 IMyClassService。 在 .Net Framework + Ninject 中,我曾经这样做:
Ninject模块
Bind< IAppServiceFactory >().ToFactory();
IAppServiceFactory class
public interface IAppServiceFactory
{
IAccessAgreementAppService AccessAgreement { get; }
IAccessAgreementUserAppService AccessAgreementUser { get; }
...
控制器
private readonly IMapper _mapper;
private readonly IAppServiceFactory _appServiceFactory;
public MyController(IMapper mapper,
IAppServiceFactory appServiceFactory)
{
_mapper = mapper;
_appServiceFactory = appServiceFactory;
}
public ActionResult Index()
{
var all = _appServiceFactory.AccessAgreementUser.GetAll();
}
主要原因是有一个更干净的控制器,而不是
private readonly IAccessAgreementAppService _accessAgreementAppService;
private readonly IAccessAgreementUserAppService _accessAgreementUserAppService;
...
public MyController(IAccessAgreementAppService accessAgreementAppService,
IAccessAgreementUserAppService accessAgreementUserAppService,
...
您可以申请 IServiceProvider
并自行获取服务。
public MyController(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IAccessAgreementAppService();
var all = service.GetAll();
}
}