• 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);        
            }
     }

  • 相关阅读:
    编写一个供浏览器端使用的NPM包
    针对低网速的性能优化
    前端性能优化之WebP
    Openwrt自定义CGI实现
    论用户体验测试:牛逼的功能千篇一律,好的用户体验万里挑一
    Vue 依赖收集原理分析
    怎么去写好一段优雅的程序
    hdu 1085 有num1个 1 ,num2个 2 ,num3个 5 (母函数)
    hdu 1398 整数划分变形 (母函数)
    hdu 1028 整数划分 (母函数)
  • 原文地址:https://www.cnblogs.com/pzxnet/p/12856413.html
Copyright © 2020-2023  润新知