本文介绍了Asp.Net MVC 5自定义操作过滤器StructureMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题,asp.net mvc的定制acitonfilte使用structuremap
在我的LogAttribute类我有setter方法​​的依赖注入正在执行我的customfilterclass的OnActionExecuted方法,这是LogAttribute即将到来的时候空

我LogAttribute类code是

 公共类LogAttribute:ActionFilterAttribute
{
    公共ApplicationDbContext上下文{搞定;组; }
    公共字符串描述{搞定;组; }
    公共LogAttribute(字符串描述)
    {
        说明=描述;
    }    公共覆盖无效OnActionExecuted(ActionExecutedContext filterContext)
    {
        变种用户id = filterContext.HttpContext.User.Identity.GetUserId();
        VAR用户= Context.Users.Find(用户ID); **我在这里得到错误的上下文来这里空**
        Context.Logs.Add(新记录(用户,filterContext.ActionDescriptor.ActionName,
                                filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                描述
                                )
                        );
        Context.SaveChanges();
    }
}

我创造另一个类从wheren我传递价值给setter依赖属性。

 公共类StructureMapFilterProvider:FilterAttributeFilterProvider
{
    私人只读Func键<&的IContainer GT; _容器;
    公共StructureMapFilterProvider(Func键<&的IContainer GT;集装箱)
    {
        _container =容器;
    }    公共覆盖的IEnumerable<滤光器> GetFilters(ControllerContext controllerContext,ActionDescriptor actionDescriptor)
    {
        VAR过滤器= base.GetFilters(controllerContext,actionDescriptor);
        变种容器= _container();
        的foreach(在过滤器变种过滤器)
        {
            container.BuildUp(filter.Instance);
            产生回油过滤器;
        }
    }
}

我的依赖解析器类code是

 公共类StructureMapDependencyResolver:的IDependencyResolver
{
    私人只读Func键<&的IContainer GT; _containerFactory;
    公共StructureMapDependencyResolver(Func键<&的IContainer GT; ContainerFactory通过)
    {
        _containerFactory = ContainerFactory通过;
    }
    公共对象GetService的(类型的serviceType)
    {
        如果(的serviceType == NULL)
        {
            返回null;
        }
        变种容器= _containerFactory();        返回serviceType.IsAbstract || serviceType.IsInterface
            ? container.TryGetInstance(的serviceType)
            :container.GetInstance(的serviceType);
    }    公共IEnumerable的<对象> GetServices(类型的serviceType)
    {
        返回_containerFactory()GetAllInstances(的serviceType).Cast<对象>();
    }
}

和我global.ascx code是

 公共类MvcApplication:System.Web.HttpApplication
{    公共集装箱的IContainer
    {
        得到
        {
            返回(的IContainer)HttpContext.Current.Items [_集装箱];
        }
        组
        {
            HttpContext.Current.Items [_集装箱] =值;
        }
    }    保护无效的Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        DependencyResolver.SetResolver(新StructureMapDependencyResolver(()=>集装箱?? ObjectFactory.Container));        ObjectFactory.Configure(CFG =>
           {
               cfg.Scan(扫描=>
               {
                   Scan.TheCallingAssembly();
                   Scan.WithDefaultConventions();
                   Scan.With(新ControllerConfiguration());
               });
               cfg.For< IFilterProvider方式>()使用(新StructureMapFilterProvider(()=>集装箱?? ObjectFactory.Container));
               cfg.For< IUserStore< ApplicationUser>>()
                  。使用< UserStore< ApplicationUser>>();
               cfg.For<&的DbContext GT;()
                  。用(()=>新建ApplicationDbContext());
               cfg.SetAllProperties(X =>
                x.Matching(P =>
                     p.DeclaringType.CanBeCastTo(typeof运算(ActionFilterAttribute))及和放大器;
                     p.DeclaringType.Namespace.StartsWith(TestingSturctureMap)及与放大器;
                     p.PropertyType.IsPrimitive&功放;&安培;
                     !p.PropertyType = typeof运算(字符串)));           });
    }    公共无效的Application_BeginRequest()
    {
        容器= ObjectFactory.Container.GetNestedContainer();
    }    公共无效Application_EndRequest()
    {
        Container.Dispose();
        集装箱= NULL;
    }
}


解决方案

亲爱的朋友们我解决我的问题,这只是[SetterProperty]从我LogAttribute类setter属性丢失

 公共类LogAttribute:ActionFilterAttribute
{
    [SetterProperty]
    公共ApplicationDbContext上下文{搞定;组; }
    公共字符串描述{搞定;组; }
    公共LogAttribute(字符串描述)
    {
        说明=描述;
    }    公共覆盖无效OnActionExecuted(ActionExecutedContext filterContext)
    {
        变种用户id = filterContext.HttpContext.User.Identity.GetUserId();
        VAR用户= Context.Users.Find(用户ID);
        Context.Logs.Add(新记录(用户,filterContext.ActionDescriptor.ActionName,
                                filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                描述
                                )
                        );
        Context.SaveChanges();
    }
}

现在它的工作:)

i am facing issue in asp.net mvc custom acitonfilte using structuremapin my "LogAttribute" class i have setter dependency injection which is coming null when executing the "OnActionExecuted" Method of my customfilterclass which is "LogAttribute"

my LogAttribute Class code is

    public class LogAttribute : ActionFilterAttribute
{
    public ApplicationDbContext Context { get; set; }
    public string Description { get; set; }
    public LogAttribute(string description)
    {
        Description = description;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var userId = filterContext.HttpContext.User.Identity.GetUserId();
        var user = Context.Users.Find(userId); **i am getting error here the Context is coming null here**
        Context.Logs.Add(new Log(user, filterContext.ActionDescriptor.ActionName,
                                filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                Description
                                )
                        );
        Context.SaveChanges();
    }
}

i creat another class from wheren i am passing value to the setter dependency property

    public class StructureMapFilterProvider : FilterAttributeFilterProvider
{
    private readonly Func<IContainer> _container;
    public StructureMapFilterProvider(Func<IContainer> container)
    {
        _container = container;
    }

    public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var filters = base.GetFilters(controllerContext, actionDescriptor);
        var container = _container();
        foreach (var filter in filters)
        {
            container.BuildUp(filter.Instance);
            yield return filter;
        }
    }
}

my dependency resolver class code is

public class StructureMapDependencyResolver : IDependencyResolver
{
    private readonly Func<IContainer> _containerFactory;
    public StructureMapDependencyResolver(Func<IContainer> containerFactory)
    {
        _containerFactory = containerFactory;
    }
    public object GetService(Type serviceType)
    {
        if (serviceType == null)
        {
            return null;
        }
        var container = _containerFactory();

        return serviceType.IsAbstract || serviceType.IsInterface
            ? container.TryGetInstance(serviceType)
            : container.GetInstance(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _containerFactory().GetAllInstances(serviceType).Cast<object>();
    }
}

and my global.ascx code is

public class MvcApplication : System.Web.HttpApplication
{

    public IContainer Container
    {
        get
        {
            return (IContainer)HttpContext.Current.Items["_Container"];
        }
        set
        {
            HttpContext.Current.Items["_Container"] = value;
        }
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => Container ?? ObjectFactory.Container));

        ObjectFactory.Configure(cfg =>
           {
               cfg.Scan(Scan =>
               {
                   Scan.TheCallingAssembly();
                   Scan.WithDefaultConventions();
                   Scan.With(new ControllerConfiguration());
               });
               cfg.For<IFilterProvider>().Use(new StructureMapFilterProvider(() => Container ?? ObjectFactory.Container));
               cfg.For<IUserStore<ApplicationUser>>()
                  .Use<UserStore<ApplicationUser>>();
               cfg.For<DbContext>()
                  .Use(() => new ApplicationDbContext());
               cfg.SetAllProperties(x =>
                x.Matching(p =>
                     p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) &&
                     p.DeclaringType.Namespace.StartsWith("TestingSturctureMap") &&
                     p.PropertyType.IsPrimitive &&
                     p.PropertyType != typeof(string)));

           });
    }

    public void Application_BeginRequest()
    {
        Container = ObjectFactory.Container.GetNestedContainer();
    }

    public void Application_EndRequest()
    {
        Container.Dispose();
        Container = null;
    }
}
解决方案

Dear friends i solve my question it was just [SetterProperty] missing from the setter property in my LogAttribute Class

    public class LogAttribute : ActionFilterAttribute
{
    [SetterProperty]
    public ApplicationDbContext Context { get; set; }
    public string Description { get; set; }
    public LogAttribute(string description)
    {
        Description = description;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var userId = filterContext.HttpContext.User.Identity.GetUserId();
        var user = Context.Users.Find(userId);
        Context.Logs.Add(new Log(user, filterContext.ActionDescriptor.ActionName,
                                filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                                Description
                                )
                        );
        Context.SaveChanges();
    }
}

now its working :)

这篇关于Asp.Net MVC 5自定义操作过滤器StructureMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 06:28