Tho*_*eil 3 asp.net-mvc dependency-injection simple-injector
我正在尝试在我的架构中实现依赖注入(MVC,DDD - 域模型,存储库).我的架构包括ASP.NET Identity 2.0.
在这个阶段,我不希望DI控制任何Identity 2.0对象(UserAdminController,RolesAdminController ......).我更喜欢DI之外的安全对象.在这个阶段,将标识对象集成到DI中看起来非常困难.我好好看看是否有人已经这样做了,所以我可以阅读并学习如何做到这一点.我找不到任何东西.(找到一个贴近但没有解决的帖子).
无论如何,我遵循Simple Injector MVC实现(参见下面的标准代码),并尝试了很多东西,我相信问题在于我调用RegisterMvcControllers.
如果我错了,请纠正我,但是这个声明会将所有控制器的名称用"控制器"后固定.
问题:如何选择使用Simple Injector注册哪些控制器?(这是手动注册吗?)
任何帮助都会非常感激,因为我今天大部分时间都在试图解决所有这些问题,然后继续下一步,即实现DI,并实例化我的对象.
...
...
...从Application_Start()调用
// Create a Simple Injector container
var container = new Container();
// Configure the container
InitializeContainer(container);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
// Verify the container's configuration
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
private static void InitializeContainer(Container container)
{
container.Register<MyService1>();
container.Register<IMyRepositoryA, MyRepositoryA>();
// Trying to include Identity into Simple Injector - please ignore
container.Register<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>(new ApplicationDbContext()));
}
Run Code Online (Sandbox Code Playgroud)
在RegisterMvcControllers将注册以下几种类型:
System.Web.Mvc.IController该RegisterMvcControllers扩展方法调用到SimpleInjectorMvcExtensions.GetControllerTypesToRegister方法来获取控制器登记的名单.您可以自己调用该方法以查看注册的内容如下:
var registeredControllerTypes =
SimpleInjectorMvcExtensions.GetControllerTypesToRegister(
container, Assembly.GetExecutingAssembly())
Run Code Online (Sandbox Code Playgroud)
因此,RegisterMvcControllers您可以通过调用GetControllerTypesToRegister方法自行注册控制器,而不是调用您:
var registeredControllerTypes =
SimpleInjectorMvcExtensions.GetControllerTypesToRegister(
container, Assembly.GetExecutingAssembly());
foreach (var controllerType in registeredControllerTypes)
{
container.Register(controllerType, controllerType, Lifestyle.Transient);
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以过滤掉要手动注册的任何控制器:
var registeredControllerTypes =
SimpleInjectorMvcExtensions.GetControllerTypesToRegister(
container, Assembly.GetExecutingAssembly())
.Where(type => type.Name != "UserStore`1");
foreach (var controllerType in registeredControllerTypes)
{
container.Register(controllerType, controllerType, Lifestyle.Transient);
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是覆盖注册:
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Options.AllowOverridingRegistrations = true;
container.Register<IUserStore<ApplicationUser>>(
() => new UserStore<ApplicationUser>(new ApplicationDbContext()))
// Always set the option back to false ASAP to prevent configuration errors.
container.Options.AllowOverridingRegistrations = false;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3169 次 |
| 最近记录: |