第一步,创建一个解决方案autoFacNetCore
第二部,添加项目名称依旧autoFacNetCore
然后呢,选择mvc
Nuget添加autoFac引用
修改StartUp文件:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();//实例化 AutoFac 容器
var assemblys = Assembly.Load("Service");//Service是继承接口的实现方法类库名称
var baseType = typeof(IDependency);//IDependency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
builder.RegisterAssemblyTypes(assemblys)
.Where(m => baseType.IsAssignableFrom(m) && m != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();
builder.Populate(services);
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器
}
ConfigureServices方法由void改为返回IServiceProvider
值得注意的两点:
1:var assemblys = Assembly.Load("Service");//Service是继承接口的实现方法类库名称
Assembly.Load("Service")中的Service是类库名称即实现继承接口的类的集合,我们这里是通过构造函数来实现依赖注入
2: var baseType = typeof(IDependency);IDependency 是一个接口,所有要实现的依赖注入的接口均需要继承IDependency
示例代码:
控制器:
using System;
using System.Collections.Generic;using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetCore.IService;
namespace autoFacNetCore.Controllers
{
public class TestController : Controller
{
public IInjectionTestService _testService;
public TestController(IInjectionTestService testService)
{
_testService = testService;
}
public string Test()
{
return _testService.Test();
}
// GET: Test
public ActionResult Index()
{
ViewBag.TestValue = _testService;
return View();
}
}
}
接口:
using System;
using System.Collections.Generic;
using System.Text;
using NetCore.Dependency;
namespace NetCore.IService
{
public interface IInjectionTestService: IDependency
{
string Test();
}
}
业务实现Service:
using System;
using System.Collections.Generic;
using System.Text;
using NetCore.IService;
namespace Service.Service
{
public class InjectionTestService: IInjectionTestService
{
public string Test()
{
return "autoFac NetCore 测试成功!";
}
}
}
源码地址github:https://github.com/zclv/autoFacNetCore