//初始化並建立一個實例
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
//註冊autofac這個容器
builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new AutofacModuleRegister()));
namespace AutoFacExample.Services.Interface {
public interface ITest {
public string GetName(string id);
}
}
using AutoFacExample.Services.Interface;
namespace AutoFacExample.Services {
public class TestService : ITest {
public string GetName(string id) {
return $"{id}:Bill";
}
}
}
AutofacModuleRegister執行批次註冊
protected override void Load(ContainerBuilder builder) {
//RegisterAssemblyTypes => 註冊所有集合
//Where(t => t.Name.EndsWith("Service")) => 找出所有Service結尾的檔案
//AsImplementedInterfaces => 找到Service後註冊到其所繼承的介面
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
}
using AutoFacExample.Services.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AutoFacExample.Controllers {
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase {
//為隱私修飾詞並且唯讀
private readonly ITest _test;
//在建構子時注入需要使用的服務
public TestController(ITest test) {
_test = test;
}
[HttpGet("GetName")]
public string Get(string id) {
//使用注入的服務
return _test.GetName(id);
}
}
}