• AutoFac mvc和WebAPI 注册Service (接口和实现)


    AutoFac  mvc和WebAPI  注册Service (接口和实现)

    1、准备组件版本:Autofac 3.5.0    Autofac.Integration.Mvc 3.3.0.0  (Install-package  Autofac.Mvc 相应版本)   Autofac.Integration.WebApi 4.0.0.0 (Install-package  Autofac.WebApi 相应版本)

      ***install-package autofac.webapi2 (注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi,否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。重写方法的          安全可访问性必须与所重写方法的安全可访问性匹配。”错误。)

    2、Global.asax  中代码:

     protected void Application_Start()
       {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
    
                // AutoFac 注入初始化
                AutoFacBootStrapper.CoreAutoFacInit();
          }

    3、实现注入类: AutoFacBootStrapper  及实现批量service注入

     public class AutoFacBootStrapper
        {
            public static void CoreAutoFacInit()
            {
               var builder = new ContainerBuilder();
                HttpConfiguration config = GlobalConfiguration.Configuration;
                //注册所有的Controllers
                builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
                #region 可正常 用
                var baseType = typeof(IDependency);
                var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
                var allServices = assemblys.SelectMany(s => s.GetTypes()).Where(p => baseType.IsAssignableFrom(p) && p != baseType);
                builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                    .AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
                //注册所有的ApiControllers
                builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
                //autofac 注册依赖
                IContainer container = builder.Build();
                // webApi部分注册
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
                #endregion 可正常用
            }
    
        }

    4、接口部分需继承 IDpendncy,该类无实现类 仅为批量注册提供标示

     public interface IDependency
        {
    
        }

    5、IService 和Servicep 实现

     public interface ICustomerService:IDependency
        {
    
              string GetCustomerName();
            
    
        }
     public class CustomerService: ICustomerService
        {
            /// <summary>
            /// 获取客户信息
            /// </summary>
            /// <returns></returns>
            public string GetCustomerName()
            {
                return "WebAPI_Success";
            }
        }

    6、Controller 调用注入类 和ApiController 调用注入类

      public class HomeController : Controller
        {
    
            public ICustomerService _customerService { get; set; }
            public ActionResult Index()
            {
                ViewBag.Title = "Home Page";
    
                return View();
            }
        }
      public class CustController : ApiController
        {
    
            public ICustomerService _customerService { get; set; }
            // GET: api/Cust
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET: api/Cust/5
            public string Get(int id)
            {
                return "value";
            }
    
            // POST: api/Cust
            public void Post([FromBody]string value)
            {
            }
    }


    至此Autofac 注入就完成了,如有问题请联系我 相互交流。qq:626382542

  • 相关阅读:
    How do I change a .txt file to a .c file?
    [CQOI2007]余数求和
    CSP-J总结&题解
    【CSP游记S】
    [LuoguP1462]通往奥格瑞玛的道路
    归并排序——逆序对
    [NOIP 2011]选择客栈
    [二分图初步]【模板】二分图匹配,匈牙利算法
    [NOIP 2018]旅行
    黑魔法师之门 (magician)-并查集
  • 原文地址:https://www.cnblogs.com/liyanbofly/p/6775197.html
Copyright © 2020-2023  润新知