zoukankan      html  css  js  c++  java
  • WebApi中的Autofac

    1.首先引用两个包

    install-package autofac
    install-package autofac.webapi2
    

    2./App_Start/IocConfig.cs

    在这个类里对依赖注入初始化

    using Autofac;
    using Autofac.Integration.WebApi;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Web;
    using System.Web.Http;
    
    namespace WebApiAutoFac.App_Start
    {
        public class IocConfig
        {
            public static void RegisterDependencies()
            {
                ContainerBuilder builder = new ContainerBuilder();
                HttpConfiguration config = GlobalConfiguration.Configuration;
                //获取正在执行的程序集
                builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
                //获取要注册的类的程序集
                Assembly[] assemblies = new Assembly[] { Assembly.Load("BLL") };
                //开始注册
                builder.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
                var container = builder.Build();
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            }
        }
    }

     3.Global 中调用上一步的初始化代码

    //依赖注入
    IocConfig.RegisterDependencies();

    4.构造函数中自动注入

    public class ProductController : ApiController
    {
            private IProductInfoRepository _productInfoRepository;
     
            //在构造函数中自动注入
            public ProductController(IProductInfoRepository productInfoRepository) {
                _productInfoRepository = productInfoRepository;
            }
    }
  • 相关阅读:
    SQL Server 幻读 的真实案例
    CSS hack 360浏览器 极速模式与兼容模式
    CS程序中XML编码Encode和解码Decode
    webbrowser 响应关闭事件
    asp.net Checkbox 绑定自定义属性
    企业库实现AOP的几种方法
    c# 自定义log4net过滤器
    SQL Server 并发死锁解决案例备忘
    c# 复制文件夹
    访问 iframe 内部控件方法
  • 原文地址:https://www.cnblogs.com/shx666/p/7898298.html
Copyright © 2011-2022 走看看