怎樣在.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();
}
}