如何使用 IocManager 在 ASP.NET 样板中注册服务?
How to register services in ASP.NET Boilerplate using IocManager?
对于 ASP.NET Core,我知道如何使用 ConfigureServices
方法在 Startup
class.
中注册服务
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x => {
var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
var factory = x.GetRequiredService<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext);
});
如何在我的 ASP.NET 样板(ASP.NET 核心)项目中使用 IocManager
注册相同的服务,以便我可以在我的应用程序服务中使用它们?
添加单例
IocManager.Register<IActionContextAccessor, ActionContextAccessor>();
AddScoped + 工厂
IocManager.IocContainer.Register(
Component
.For<IUrlHelper>()
.UsingFactoryMethod(kernel =>
{
var actionContext = kernel.Resolve<IActionContextAccessor>().ActionContext;
var factory = kernel.Resolve<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext);
})
.LifestyleCustom<MsScopedLifestyleManager>() // ASP.NET Core
// .LifestylePerWebRequest() // ASP.NET MVC 5
);
参考资料
- ASP.NET 样板文档:Dependency Injection — Custom/Direct Registration
- IoC PerWebRequest 和工厂模式:aspnetboilerplate/aspnetboilerplate#3921
- IScopedDependency:aspnetboilerplate/aspnetboilerplate#3945
对于 ASP.NET Core,我知道如何使用 ConfigureServices
方法在 Startup
class.
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x => {
var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
var factory = x.GetRequiredService<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext);
});
如何在我的 ASP.NET 样板(ASP.NET 核心)项目中使用 IocManager
注册相同的服务,以便我可以在我的应用程序服务中使用它们?
添加单例
IocManager.Register<IActionContextAccessor, ActionContextAccessor>();
AddScoped + 工厂
IocManager.IocContainer.Register(
Component
.For<IUrlHelper>()
.UsingFactoryMethod(kernel =>
{
var actionContext = kernel.Resolve<IActionContextAccessor>().ActionContext;
var factory = kernel.Resolve<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext);
})
.LifestyleCustom<MsScopedLifestyleManager>() // ASP.NET Core
// .LifestylePerWebRequest() // ASP.NET MVC 5
);
参考资料
- ASP.NET 样板文档:Dependency Injection — Custom/Direct Registration
- IoC PerWebRequest 和工厂模式:aspnetboilerplate/aspnetboilerplate#3921
- IScopedDependency:aspnetboilerplate/aspnetboilerplate#3945