相关疑难解决方法(0)

将依赖项注入ASP.NET MVC 3动作过滤器.这种方法有什么问题?

这是设置.假设我有一些需要服务实例的动作过滤器:

public interface IMyService
{
   void DoSomething();
}

public class MyService : IMyService
{
   public void DoSomething(){}
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个需要该服务实例的ActionFilter:

public class MyActionFilter : ActionFilterAttribute
{
   private IMyService _myService; // <--- How do we get this injected

   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       _myService.DoSomething();
       base.OnActionExecuting(filterContext);
   }
}
Run Code Online (Sandbox Code Playgroud)

在MVC 1/2中,将依赖关系注入动作过滤器是一个痛苦的屁股.最常见的方法是使用自定义操作调用因为在这里可以看到:http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/的这种解决方法背后的主要动机是因为以下方法被认为是与容器的草率和紧密耦合:

public class MyActionFilter : ActionFilterAttribute
{
   private IMyService _myService;

   public MyActionFilter()
      :this(MyStaticKernel.Get<IMyService>()) //using Ninject, but would apply to any container
   {

   }

   public MyActionFilter(IMyService myService)
   {
      _myService = myService;
   } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc dependency-injection actionfilterattribute asp.net-mvc-3

77
推荐指数
3
解决办法
4万
查看次数