Framework

方法1
1.1、项目情况
框架:.NET Framework 4.5
Autofac 3.5.0
Autofac.WebApi2 4.3.0

1.2、定义接口与对应实现
// 接口1
public interface IBaseUserService
{
    List<BaseUser> GetBaseUserList();
}
// 接口2
public interface IBaseCloseLoopService
{
    List<BaseCloseLoop> GetBaseCloseLoopList();
}
 
// 实现1
public class BaseUserService : IBaseUserService
{
    public List<BaseUser> GetBaseUserList()
    {
        BaseUserDao dao = new BaseUserDao();
        return dao.GetModelList();
    }
 
}
// 实现2
public class BaseCloseLoopService : IBaseCloseLoopService
{
    public List<BaseCloseLoop> GetBaseCloseLoopList()
    {
        BaseCloseLoopDao dao = new BaseCloseLoopDao();
        return dao.GetModelList();
    }
}
 1.3、添加Autofac配置类
public class AutofacConfig
{
    public static Autofac.IContainer _container;
 
    public static void Configure()
    {
        var builder = new ContainerBuilder();
        var config = System.Web.Http.GlobalConfiguration.Configuration;
 
        // OPTIONAL: Register the Autofac filter provider.
        //builder.RegisterWebApiFilterProvider(config);
        // OPTIONAL: Register the Autofac model binder provider.
        //builder.RegisterWebApiModelBinderProvider();
            
        // 指定接口的实现类
        builder.RegisterType<BaseUserService>().As<IBaseUserService>().AsImplementedInterfaces();
        builder.RegisterType<BaseCloseLoopService>().As<IBaseCloseLoopService>().AsImplementedInterfaces();
        // 一次性注册所有【实现了baseTyp接口的类】;不建议,无法指定接口实现类
        //Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
        //List<Type> baseTypeList = new List<Type>()
        //{
        //    typeof(IBaseUserService),
        //    typeof(IBaseCloseLoopService)
        //};
        //builder.RegisterAssemblyTypes(assemblies).Where(type => baseTypeList.Any(t => t.IsAssignableFrom(type)) && !type.IsAbstract).AsSelf().AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
 
        // 注册 Web API Controllers
        builder.RegisterApiControllers(System.Reflection.Assembly.GetExecutingAssembly());
        _container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(_container);
    }
}
 
 
 
// ================================ 分割线 ==========================================
 
// 以下为ASP.NET MVC的Autofac配置,注意引用的DLL有所不同,此处不详述
public class AutofacConfig
{
    public static Autofac.IContainer _container;
    public static void Register()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<BaseCloseLoopService>().As<IBaseCloseLoopService>();
        builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
        _container = builder.Build();
        System.Web.Mvc.DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(_container));
    }
}
1.4、在Global.asax引用配置
public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
 
        //autofac ioc配置
        AutofacConfig.Configure();
    }
}
1.5、ApiController使用
public class CloseLoopController : ApiController
{
    // 需要注入的接口
    private readonly IBaseUserService _baseUserService;
    private readonly IBaseCloseLoopService _baseCloseLoopService;
    /// <summary>
    /// 构造函数注入
    /// </summary>
    /// <param name="baseUserService"></param>
    /// <param name="baseCloseLoopService"></param>
    public CloseLoopController(IBaseUserService baseUserService, IBaseCloseLoopService baseCloseLoopService)
    {
        _baseUserService = baseUserService;
        _baseCloseLoopService = baseCloseLoopService;
    }
 
 
    [HttpGet]
    public string GetBaseUser([FromBody] object json)
    {
        // 直接调用方法即可
        var result = _baseUserService.GetBaseUserList();
        return JsonConvert.SerializeObject(result);
    }
 
    [HttpGet]
    public string GetBaseCloseLoop([FromBody] object json)
    {
        var result = _baseCloseLoopService.GetBaseCloseLoopList();
        return JsonConvert.SerializeObject(result);
    }
 
}
方法2
2.1、安装包
前面方法1的前提下,再Nuget安装 Autofac.Configuration 

2.2、web.config配置autofac
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />
    </configSections>
    <autofac>
        <components>
            <component type="Autofac.Test.Service.BaseUserService, Autofac.Test.Service" service="Autofac.Test.Contracts.IBaseUserService, Autofac.Test.Contracts" />
            <component type="Autofac.Test.Service.BaseCloseLoopService, Autofac.Test.Service" service="Autofac.Test.Contracts.IBaseCloseLoopService, Autofac.Test.Contracts" />
        </components>
    </autofac>
</configuration>
2.3、新建autofac帮助类,读取配置生成实例
using Autofac;
using Autofac.Configuration;
 
public class IOCHelper
{
    public static TInterface GetObject<TInterface>(string sectionName)
    {
        Autofac.ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterModule(new Autofac.Configuration.ConfigurationSettingsReader(sectionName));
        IContainer container = builder.Build();
        TInterface dal = container.Resolve<TInterface>();
        return dal;
    }
}
2.4、调用
private IBaseUserService userService = IOCHelper.GetObject<IBaseUserService>("autofac");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值