zoukankan      html  css  js  c++  java
  • .net mvc web api Autofac依赖注入框架-戈多编程

    今天自己搭了一套基于三层的依赖注入mvc web api 的依赖注入框架,在此总结下相关配置

    1.设置应用程序的.net Framework版本为 4.5

    2.通过Nuget 安装autofac包

    Install-Package Autofac

    Install-Package Autofac.WebApi

    3.引用如下命名空间

    using Autofac;
    using Autofac.Integration.WebApi;
    using Autofac.Integration.Mvc;
    using System.Web.Mvc;

    4.再按照如下代码配置Autofac(分别搭建DAL、BLL、IDAL、IBLL)

    public static void Register()
    {
    var builder = new ContainerBuilder();
    HttpConfiguration configuration = GlobalConfiguration.Configuration;
    var assemblyList = AppDomain.CurrentDomain.GetAssemblies();


    builder.RegisterWebApiFilterProvider(configuration);




    //var iServices = Assembly.Load("IOC.IBLL");
    //var services = Assembly.Load("IOC.BLL");
    //var iRepository = Assembly.Load("IOC.IDAL");
    //var repository = Assembly.Load("IOC.DAL");

    //builder.RegisterAssemblyTypes(iServices, services)
    // .Where(t => t.Name.EndsWith("Service"))
    // .AsImplementedInterfaces();

    //var test = builder.RegisterAssemblyTypes(iRepository, repository)
    // .Where(t => t.Name.EndsWith("Dal"))
    // .AsImplementedInterfaces();


    builder.RegisterAssemblyTypes(assemblyList)
    .Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Dal"))
    .AsImplementedInterfaces();

    builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //注册所有controller
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //注册所有apicontroller

    var container = builder.Build();

    configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注册api容器
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//注册mvc容器
    }

    5.在Application_Start里调用 AutofacConfig.Register();

    6.然后在每一层采用构造函数依赖注入方式。

  • 相关阅读:
    可持久化线段树区间查询 + 永久化标记 T^T online judge 2507
    可持久化线段树
    T^T online judge 3441
    食物链
    T^T ONLINE JUDGE 2592
    HDU 6312 GAME
    HDU 1430 魔板
    栈的操作链表+数组版
    Codeforces Round #468 (Div. 2, based on Technocup 2018 Final Round) D. Peculiar apple-tree
    Codeforces Round #468 (Div. 2, based on Technocup 2018 Final Round) C. Laboratory Work
  • 原文地址:https://www.cnblogs.com/geduocoding/p/7364709.html
Copyright © 2011-2022 走看看