MVC 3/2团结依赖注射过滤器? [英] Mvc 3/Unity 2 inject dependencies into a Filter?
问题描述
我怎么可以注入下面的依赖??
How can i inject the following dependencies ??
public class Authenticate : AuthorizeAttribute
{
[Dependency]
public IAuthenticate AuthenticateLibrary { get; set; }
[Dependency]
public ILibrary BaseLibrary { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
}
我使用Unity 2注入所有控制器。是否有统一2教程和依赖注入到过滤器?
I am using Unity 2 to inject all the controllers. Is there a tutorial for Unity 2 and injecting dependencies into filters?
推荐答案
布拉德·威尔逊对服务定位一个很好的系列,其中包括如何创建可以支持依赖注入自己的过滤器提供商:<一href=\"http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html\">http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html (向下滚动到部分添加依赖注入到过滤器)。
Brad Wilson has a good series on Service Location which includes how to create your own filter provider that can support dependency injection: http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html (Scroll down to the section "Adding Dependency Injection to Filters").
- 复制code,他提供了UnityFilterAttributeFilterProvider.cs。
UnitFilterAttributeFilterProvider.cs
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider {
private IUnityContainer _container;
public UnityFilterAttributeFilterProvider(IUnityContainer container) {
_container = container;
}
protected override IEnumerable<FilterAttribute> GetControllerAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
var attributes = base.GetControllerAttributes(controllerContext,
actionDescriptor);
foreach (var attribute in attributes) {
_container.BuildUp(attribute.GetType(), attribute);
}
return attributes;
}
protected override IEnumerable<FilterAttribute> GetActionAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
var attributes = base.GetActionAttributes(controllerContext,
actionDescriptor);
foreach (var attribute in attributes) {
_container.BuildUp(attribute.GetType(), attribute);
}
return attributes;
}
}
- 修改的global.asax.cs的的Application_Start使UnityFilterAttributeFilterProvider过滤器提供商为您MVC应用程序。
。
protected void Application_Start() {
// ...
var oldProvider = FilterProviders.Providers.Single(
f => f is FilterAttributeFilterProvider
);
FilterProviders.Providers.Remove(oldProvider);
var container = new UnityContainer();
var provider = new UnityFilterAttributeFilterProvider(container);
FilterProviders.Providers.Add(provider);
// ...
}
- 装饰要团结注入用于与[依赖]属性值的属性。然后,你要善于去。
这篇关于MVC 3/2团结依赖注射过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!