【发布时间】:2017-08-01 23:35:42
【问题描述】:
我有一个自定义的WebViewPage,我希望 SimpleInjector 解决其中的一些依赖关系。由于 MVC 实例化此类的方式,我似乎无法使用构造函数注入。
我已启用显式属性注入,如 SimpleInjector documentation 中所述。但是属性没有被注入——它们总是null。
自定义 WebViewPage 类:
public abstract class CustomWebViewPage<T> : WebViewPage<T>
{
[Import]
public IMyDependency Dependency { get; set; }
public void UseDependency()
{
Dependency.DoStuff(); // Dependency is null
}
}
IOC 设置:
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Register<IMyDependency, MyDependency>();
我是否需要连接其他任何东西才能使其正常工作?我尝试使用 SimpleInjector 注册自定义 WebViewPage(将 WebViewPage<> 映射到 CustomWebViewPage<> 并使我的课程非抽象),但这也不起作用。
需要明确的是,所有其他属性和构造函数依赖注入都在应用程序中工作 - 只是不适用于这个特定的类。
【问题讨论】:
-
有这个相关的问题 - stackoverflow.com/questions/38704650 - 但这是关于在视图中使用自定义 WebViewPage 类的内容。这一点对我来说很好,但不是属性注入。
-
如果我没有理解错 - 你是说 MVC 不允许构造函数注入???(因为我只通过构造函数注入控制器的依赖项)
-
It seems like I can't use constructor injection due to the way MVC instantiates this class这很奇怪。你看过这个吗? :stackoverflow.com/questions/19925290/… -
@Rudresha - 是的,当然 MVC 允许构造函数注入,我在所有控制器中都使用它。但它似乎不适用于自定义 WebViewPage 类。不过,我很可能做错了什么。
-
你考虑过这句话吗:
But as the others said you shouldn't do view injection anyway. Your view should be dumb and just render the view model to HTML. Anything requiring a dependency should be done in the controller or a service.?
标签: c# asp.net-mvc-4 simple-injector