风轻云淡

-------生活没有抱怨,只有自己的不努力,当才华撑不起梦想与野心,不断学习是你唯一的选择。没有伞的孩子必须努力奔跑...

导航

Autofac依赖注入之AuthorizeAttribute属性注入---.net framework 4.5 Mvc5 WebApi

1、Webapi框架下使用Autofac属性注入之----AuthorizeAttribute的属性注入

 public class MyAuthorizeAttribute : AuthorizeAttribute
    {

       public MyLog log { get; set; } //autofac注入的属性
        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {

                log.Message("验证信息...");

        }

}

2、在WebApiConfig.cs文件中添加配置代码:

  public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //依赖注入初始化
            AutofacBuilder.Init(config);
        }
    }

 

3、新建一个autofac依赖注入配置文件:AutofacBuilder.cs

 public class AutofacBuilder
  {
        public static void Init(HttpConfiguration config)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());


            builder.RegisterType<MyLog>().As<MyLog>(); //MyLog也可以写成接口 ==>> builder.RegisterType<MyLog>().As<IMyLog>();

            //builder.RegisterFilterProvider();

            builder.RegisterWebApiFilterProvider(config);


            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().AsSelf();
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));            
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);        
        }
 }

 

posted on 2020-05-09 11:55  淡然→笑  阅读(820)  评论(0编辑  收藏  举报