Autofac +webapi 配置

Autofac配置

 

using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;

namespace WebAutoFac
{
    /// <summary>
    /// Autofac配置
    /// </summary>
    public class AutoFacBootStrapper
    {
        /// <summary>
        /// Autofac配置
        /// </summary>
        public static void CoreAutoFacInit()
        {
            #region MVC---install-package autofac.mvc5 注意版本

            //var builder = new ContainerBuilder();

            //SetupResolveRules(builder);

            ////注册所有的Controllers
            //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            //var container = builder.Build();
            //System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            #endregion

            #region Webapi和MVC ---install-package autofac.mvc5 install-package autofac.webapi2 注意版本

            var builder = new ContainerBuilder();
            SetupResolveRules(builder);

            //注册所有的Controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            //注册所有的ApiControllers
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();

            var container = builder.Build();
            //注册所有的Controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            //注册api容器需要使用HttpConfiguration对象
            HttpConfiguration config = GlobalConfiguration.Configuration;
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            
            #endregion
            

            #region 自动注入 --- 注释

            ////创建autofac管理注册类的容器实例
            //var builder = new ContainerBuilder();
            //HttpConfiguration config = GlobalConfiguration.Configuration;
            //Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
            ////注册所有实现了 IDependency 接口的类型
            //Type baseType = typeof(IDependency);
            //builder.RegisterAssemblyTypes(assemblies)
            //       .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
            //       .AsSelf().AsImplementedInterfaces()
            //       .PropertiesAutowired().InstancePerLifetimeScope();
            ////注册MVC类型
            //// builder.RegisterControllers(assemblies).PropertiesAutowired();
            ////注册Api类型
            //builder.RegisterApiControllers(assemblies).PropertiesAutowired();
            ////builder.RegisterFilterProvider();
            //builder.RegisterWebApiFilterProvider(config);
            //var container = builder.Build();
            ////注册api容器需要使用HttpConfiguration对象
            //config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            ////注册解析
            //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            #endregion

            //有了 IDependency 这个基接口,我们只需要 Global 中很简单的几行代码,就可以完成整个系统的依赖注入匹配
            //ContainerBuilder builder = new ContainerBuilder();
            //builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));
            //Type baseType = typeof(IDependency);

            //// 获取所有相关类库的程序集
            //Assembly[] assemblies = ...

            //builder.RegisterAssemblyTypes(assemblies)
            //    .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
            //    .AsImplementedInterfaces().InstancePerLifetimeScope();//InstancePerLifetimeScope 保证对象生命周期基于请求
            //IContainer container = builder.Build();
            //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        private static void SetupResolveRules(ContainerBuilder builder)
        {
            //WebAPI只用引用services和repository的接口,不用引用实现的dll。
            //如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll
            var iServices = Assembly.Load("IBLL");
            var services = Assembly.Load("BLL");
            //var iRepository = Assembly.Load("WebAPI.IRepository");
            //var repository = Assembly.Load("WebAPI.Repository");

            //根据名称约定(服务层的接口和实现均以Services结尾),实现服务接口和服务实现的依赖
            builder.RegisterAssemblyTypes(iServices, services)
              .Where(t => t.Name.EndsWith("BLL"))
              .AsImplementedInterfaces();

            ////根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖
            //builder.RegisterAssemblyTypes(iRepository, repository)
            //  .Where(t => t.Name.EndsWith("Repository"))
            //  .AsImplementedInterfaces();

            //var cont = Assembly.Load("WebAutoFac");
            ////根据名称约定(服务层的接口和实现均以Services结尾),实现服务接口和服务实现的依赖
            //builder.RegisterAssemblyTypes(cont)
            //  .Where(t => t.Name.EndsWith("Controller"))
            //  .AsImplementedInterfaces();

            ////使用新的覆盖旧的注册DLL-使用UserNew代替UserOld
            //builder.RegisterType<BLL.UserBLL>().As<IBLL.IUserBLL>();

        }
    }
}
View Code

 

using Autofac;
using BLL;
using IBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;

namespace WebAutoFac.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [RoutePrefix("User")]
    public class UserController : ApiController
    {
        private IUserBLL _userBll;
        private IPeopleBLL _peopleBll;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userBLL"></param>
        /// <param name="peopleBll"></param>
        public UserController(IUserBLL userBLL, IPeopleBLL peopleBll)
        {
            _userBll = userBLL;
            _peopleBll = peopleBll;
        }
        /// <summary>
        /// 最原始的方式直接new(需添加对BLL层的引用)
        /// </summary>
        /// <returns></returns>
        [HttpGet,Route("Refernce")]
        public string GetUserInfoByRefernce()
        {
            UserBLL userBll = new UserBLL();
            var result = userBll.GetUserInfor();
            return result;
        }

        /// <summary>
        /// 面向接口编程(仍需添加对BLL层的引用)
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("Interface")]
        public string GetUserInfoByInterface()
        {
            IUserBLL userBll = new UserBLL();
            var result = userBll.GetUserInfor();
            return result;
        }
        /// <summary>
        /// 接口+反射(只需将BLL层的程序集拷贝进来)
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("Reflection")]
        public string GetUserInfoByReflection()
        {
            Assembly ass = Assembly.Load("BLL.dll");
            Type type = ass.GetType("BLL.UserBLL");
            //调用默认的无参构造函数进行对象的创建
            object myUserBll = Activator.CreateInstance(type);
            IUserBLL userBll = myUserBll as IUserBLL;
            var result = userBll.GetUserInfor();
            return result;
        }

        /// <summary>
        /// 测试AUTOFAC
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("testAutofac")]
        public string Test()
        {
            //IUserBLL userBLL = System.Web.Mvc.DependencyResolver.Current.GetService<IUserBLL>();
            var builder = new ContainerBuilder();
            builder.RegisterType<UserBLL>().As<IUserBLL>();
            var container = builder.Build().BeginLifetimeScope();
            var userBll = container.Resolve<IUserBLL>();
            var result = userBll.GetUserInfor("Autofac");
            return result;
            //var result = _userBLL.GetUserInfor("Autofac");
            //return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("Assembly")]
        public string GetUserInfo()
        {
            //1、使用nupkg引用Autofac,Autofac.Mvc5和Autofac.Webapi2
            //PM > install-package autofac - version 3.5.0
            //PM > install-package autofac.mvc5
            //PM > install-package autofac.webapi2
            //(注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi, 
            //否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。
            //重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。”错误。) mvc同样
            string strUserInfo = _userBll.GetUserInfor("user-Assembly");
            string strPeople = _peopleBll.Introduce("people-Assembly");
            string result = strUserInfo + "," + strPeople;
            return result;
        }

        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}
UserController

 

netcore;

 //DI了AutoMapper中需要用到的服务,其中包括AutoMapper的配置类 Profile
            services.AddAutoMapper();
            var builder = new ContainerBuilder();
            builder.Populate(services);
            builder.RegisterAssemblyTypes(typeof(ManagerRoleRepository).Assembly)
                   .Where(t => t.Name.EndsWith("Repository"))
                   .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof(ManagerRoleService).Assembly)
                 .Where(t => t.Name.EndsWith("Service"))
                 .AsImplementedInterfaces();
            return new AutofacServiceProvider(builder.Build());
        }
netcore 配置

 

public IServiceProvider ConfigureServices(IServiceCollection services)
        { 
            services.AddMvc();
            var builder = new ContainerBuilder();//实例化 AutoFac  容器   
              
            var assemblys = Assembly.Load("Service");//Service是继承接口的实现方法类库名称
            var baseType = typeof(IDependency);//IDependency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
            builder.RegisterAssemblyTypes(assemblys)
             .Where(m => baseType.IsAssignableFrom(m) && m != baseType)
             .AsImplementedInterfaces().InstancePerLifetimeScope();


            builder.Populate(services);
            ApplicationContainer = builder.Build();
            return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器

        }

ConfigureServices方法由void改为返回IServiceProvider
View Code

 

 

 

https://www.cnblogs.com/shacoli/p/8523866.html

https://www.cnblogs.com/xujie520/p/5200815.html

https://www.cnblogs.com/yanweidie/p/autofac.html

https://www.cnblogs.com/lenmom/p/9081658.html

https://blog.csdn.net/ad996454914/article/details/80901105

https://www.cnblogs.com/yanweidie/p/autofac.html

posted @ 2019-02-21 17:00  bxzjzg  阅读(262)  评论(0编辑  收藏  举报