使用 Castle Windsor 将依赖项注入 CustomAttribute
在我的 ASP.Net MVC 应用程序中,我实现了一个自定义 ActionFilter 来授权用户。
我使用 CastleWindsor 向所有控制器提供依赖项注入,如下所示:
protected virtual IWindsorContainer InitializeServiceLocator()
{
IWindsorContainer container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
container.RegisterControllers(typeof(HomeController).Assembly);
ComponentRegistrar.AddComponentsTo(container);
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
return container;
}
在我的 CustomAttribute 中,我需要一个由所有控制器使用的依赖项,但是我无法在属性中使用基于构造函数的注入。
那么最干净的出路是什么?我如何提供依赖关系?
In my ASP.Net MVC application I have implemented a Custom ActionFilter to Authorize users.
I use CastleWindsor to provide dependency injection into all of the controllers as follows:
protected virtual IWindsorContainer InitializeServiceLocator()
{
IWindsorContainer container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
container.RegisterControllers(typeof(HomeController).Assembly);
ComponentRegistrar.AddComponentsTo(container);
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
return container;
}
Within my CustomAttribute, I need a dependency that is used by all of my controllers, however I am unable to user Constructor based injection in an attribute.
So what's the cleanest way out here? How can I provide the dependency?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的 - 这似乎是 使用 ASP MVC 和 Castle Windsor 将数据库注入验证属性,这已得到解答。
另外 如何使用 Windsor 进行注入依赖于 ActionFilterAttributes。
阅读完上述内容和引用的文章后 - 对我来说最重要的是 http://weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc-actionfilters.aspx 适合任何人还有谁有兴趣。
OK - this seems to be a duplicate of Database injection into a validation attribute with ASP MVC and Castle Windsor which has been answered.
Also How do I use Windsor to inject dependencies into ActionFilterAttributes.
Having read through the above, and the referenced articles - the key one for me is http://weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc-actionfilters.aspx for anyone else who is interested.
你不能。属性是元数据。将行为放入其中是错误的。放置依赖项更糟糕。
使用您的属性作为标记来表示您想要应用该行为并在其他地方实现该行为的对象。
在 MVC 中,“其他地方”通常意味着自定义操作调用程序,它使用属性中的数据来提供您所需的行为。
You can't. Attributes are metadata. Putting behaviour into them is wrong. Putting dependencies is even worse.
Use your attribute as marker to denote objects to which you want to apply the behavior and implement the behavior elsewhere.
In MVC elsewhere usually means a custom action invoker that uses data from the attribute to provide the behavior you need.