ASP.NET WebApi + Autofac 实现依赖注入

一、项目情况

框架:.NET Framework 4.5
Autofac 3.5.0
Autofac.WebApi2 4.3.0

ASP.NET WebApi + Autofac 实现依赖注入_第1张图片

二、定义接口与对应实现

// 接口1
public interface IBaseUserService
{
    List GetBaseUserList();
}
// 接口2
public interface IBaseCloseLoopService
{
    List GetBaseCloseLoopList();
}

// 实现1
public class BaseUserService : IBaseUserService
{
    public List GetBaseUserList()
    {
        BaseUserDao dao = new BaseUserDao();
        return dao.GetModelList();
    }

}
// 实现2
public class BaseCloseLoopService : IBaseCloseLoopService
{
    public List GetBaseCloseLoopList()
    {
        BaseCloseLoopDao dao = new BaseCloseLoopDao();
        return dao.GetModelList();
    }
}

 三、添加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().As().AsImplementedInterfaces();
        builder.RegisterType().As().AsImplementedInterfaces();
        // 一次性注册所有【实现了baseTyp接口的类】;不建议,无法指定接口实现类
        //Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
        //List baseTypeList = new List()
        //{
        //    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().As();
        builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
        _container = builder.Build();
        System.Web.Mvc.DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(_container));
    }
}

四、在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();
    }
}

五、ApiController使用

public class CloseLoopController : ApiController
{
    // 需要注入的接口
    private readonly IBaseUserService _baseUserService;
    private readonly IBaseCloseLoopService _baseCloseLoopService;
    /// 
    /// 构造函数注入
    /// 
    /// 
    /// 
    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);
    }

}

你可能感兴趣的:(C#,asp.net,asp.net,后端,c#)