怎样在.netcore MVC里面利用autofac实现管道注入?
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var builder = new ContainerBuilder();
builder.Populate(services);
Type basetype = typeof(IDenpendency);
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => basetype.IsAssignableFrom(t) && t.IsClass)
.AsImplementedInterfaces().InstancePerLifetimeScope();
var Container = builder.Build();
return new AutofacServiceProvider(Container);
}
直接修改Startup.cs里面的ConfigureServices方法,入上面的代码
这里面用到了autofac的批量注入功能,可以参考之前写的日志,链接如下:https://blog.csdn.net/xiaxiaoying2012/article/details/84617677
怎样在controller里面实用注入的接口呢?
首先新建一个功能接口
public interface IFoo:IDenpendency
{
string GetName();
}
注意:该接口要先继承IDenpendency
然后创建一个继承于IFoo的实现类
public class Foo : IFoo
{
private string guid;
public string Name { get; set; }
public Foo()
{
guid = Guid.NewGuid().ToString();
}
public string GetName()
{
return guid;
}
}
最后在controller里面按照如下方法调用
public class TestController : Controller
{
private IFoo foo;
public TestController(IFoo foo) //利用autofac的构造函数注入方法注入接口
{
this.foo = foo;
}
public IActionResult Index()
{
IFoo foo1 = (IFoo)HttpContext.RequestServices.GetService(typeof(IFoo)); //利用mvc自带的 HttpContext.RequestServices.GetService方法调用注入的接口
string guid1 = foo1.GetName();
string guid2 = foo.GetName();
return View();
}
}