[英]ASP.NET MultiLayer App Migration To ASP.NET Core
I migrate my ASP.NET multi layer project to ASP.NET Core. 我将ASP.NET多层项目迁移到ASP.NET Core。 I was using Ninject for DI in my old project and i could call it as follow in my BLL.
我在我的旧项目中使用Ninject进行DI,我可以在BLL中将其称为。
public void IamMethodInBll()
{
...
//i could call ninject like this.
var prodCalcManager = Const.NinjectKernel.Get<IProdCalcService>();
prodSurr.CalculatedPrice = prodCalcManager.GetMyMethod()
..
}
In now i use ASP Net Core's DI system of course. 现在我使用ASP Net Core的DI系统。 But how can i call the service locator in business layer for ASP.NET core?
但是如何在ASP.NET核心的业务层中调用服务定位器? I need your samples and suggestions.
我需要你的样品和建议。
In Startup.cs 在Startup.cs中
services.AddScoped<IProdCalcService,ProdCalcManager>();
In BLL 在BLL
public void IamMethodInBll()
{
...
//What's the proper way to call another service in BLL
//How can i get the service provider in BLL
var prodCalcManager = _serviceProvider.GetService<IProdCalcService>();
prodSurr.CalculatedPrice = prodCalcManager.GetMyMethod()
..
}
The correct answer is: Dont use ServiceLocator. 正确答案是:不要使用ServiceLocator。 Register your services using the
services.AddScoped<T>
like you are and then add that to the constructor of the class you want to use it in. 使用
services.AddScoped<T>
注册您的服务,然后将其添加到要使用它的类的构造函数中。
Like so: 像这样:
services.AddScoped<IProdCalcService,ProdCalcManager>();
Then your class looks like this: 然后你的班级看起来像这样:
public class MyClass()
{
private IProdCalcService calcService;
public MyClass(IProdCalcService calcService)
{
this.calcService = calcService;
}
public void IamMethodInBll()
{
//...
prodSurr.CalculatedPrice = calcService.GetMyMethod();
//...
}
}
It is better to DONT USE Service Locator but in this case you can inject ServiceProvider to your Controller or better solution is wrap and abstract ServiceProvider in a Container that can be injectable simply. DONT USE服务定位器更好,但在这种情况下,您可以将ServiceProvider注入您的Controller,或者更好的解决方案是在一个可以简单注入的Container中包装和抽象ServiceProvider。 I prefer to use 3rd party DI Containers for use in this situation, specially CastleCore can be good choice.
我更喜欢在这种情况下使用第三方DI容器,特别是CastleCore可能是不错的选择。
public interface IContainer
{
T Resolve<T>();
}
public class ServiceProviderContainer : IContainer
{
private IServiceProvider _serviceProvider;
public ServiceProviderContainer(IServiceProvider serviceProvider)
{
this._serivceProvider = serviceProvider;
}
public T Resolve<T>()
{
return _seriveProvider.GetService<T>();
}
}
public class MyController : Controller
{
private IContainer contianer;
public MyController(IContainer container)
{
this._container = container;
}
public IActionResult Get()
{
var service = _container.Resolve<IUserRepository>();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.