【代码】Autofac在WebApi中基本的使用方法

2022-03-23 16:00:34  阅读 2690 次 评论 0 条

本篇文章用构造器注入进行示例,做的不对的地方,欢迎指出。做的不好的地方,大佬轻喷。

本篇文章是在已经建立好其他层(业务逻辑,数据访问)的情况下进行操作,建立的步骤我就不写了,本篇只是简单的实现,方便理解。

我的目录结构

image.png

1.先从Nuget下载这几个包

image.png

2.建立AutoFacRegister类

 public class AutoFacRegister
    {
        public static void Regist()
        {
            HttpConfiguration config = GlobalConfiguration.Configuration;
            ContainerBuilder builder = new ContainerBuilder();
            //builder.RegisterControllers(Assembly.GetExecutingAssembly());//这个是注册MVC的
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());//注册所有Api控制器

            //需要注册类所在的dll
            Assembly[] assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(y=>y.CodeBase.ToLower().Contains("ygmxapi.bo.dll")|| y.CodeBase.ToLower().Contains("ygmxapi.dao.dll")).ToArray();

            //注册所有Bo结尾的类,这个是业务逻辑层,命名规则根据自己的实际情况而定
            builder.RegisterAssemblyTypes(assemblies).Where(y => y.Name.EndsWith("Bo")).AsImplementedInterfaces();
            //builder.RegisterAssemblyTypes(assemblies).Where(y => y.Name.EndsWith("Dao")).AsImplementedInterfaces();
            
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注册API容器需要使用HttpConfiguration对象
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }

3.程序启动注入(Global.asax)

 public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //程序启动注入
            AutoFacRegister.Regist();
        }
    }

4.接口调用数据:在接口中,就可以用构造方法来初始化Bo

 public class TestController : ApiController
    {
        TestBo _tbo = null;
        //构造器注入Bo
        public TestController(TestBo tbo)
        {
            _tbo = tbo;
        }
       
       
        public string Index()
        {
            //这个是路由配置的,想了解的可以去搜索相关路由配置的文章
            string uname = RequestContext.RouteData.Values["uname"].ToString();
            string res=_ibo.sayHello(uname);
            return res;            
        }
    }

在Business中也一样

 public class TestBo : ITestBo 
    {
        private ITestDao _tdao;
        public TestBo(ITestDao tdao)
        {
            _tdao = tdao;
        }
        public string sayHello(string name)
        {
            string res= name + ":来自Bo。";
            res += _tdao.sayHello(name);
            return res;
        }
    }



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2197
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?