IOC使用
Posted menbe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOC使用相关的知识,希望对你有一定的参考价值。
1.public static void InitAutoFac()
{
//得到你的HttpConfiguration.
var configuration = GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
//注册控制器
//builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
////可选:注册Autofac过滤器提供商.
//builder.RegisterWebApiFilterProvider(configuration);
var webapiAssembly = Assembly.Load("SpecialtyTests.API");
builder.RegisterAssemblyTypes(webapiAssembly);
var bll = Assembly.Load("SpecialtyTests.BLL");
builder.RegisterAssemblyTypes(bll);
var _interfaceType = typeof(IDALBase);
/*注册的DAL*/
builder.RegisterAssemblyTypes(Assembly.Load("SpecialtyTests.DAL")).Where(m => _interfaceType.IsAssignableFrom(_interfaceType)).AsImplementedInterfaces().InstancePerLifetimeScope();
IContainer container = builder.Build();
//将依赖关系解析器设置为Autofac。
var resolver = new AutofacWebApiDependencyResolver(container);
configuration.DependencyResolver = resolver;
}
}
2.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AutoFacConfig.InitAutoFac();//调用InitAutoFac()方法执行
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
using Autofac;
using Autofac.Integration.WebApi;
3.把方法写接口里
UserInterFace dal;
public UserLoginBll(UserInterFace user)
{
dal = user;
}
以上是关于IOC使用的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot在IOC之外的类中使用IOC内部的Bean