天天看點

【案例分享】Asp.net Core內建Autofac

作者:DotNet布道師

1、簡介

使用依賴注入架構能更好的管理對象的生命周期,能減少業務之間的依賴程度。在c#中有很多依賴注入插件,比較流行的有自帶注入,Autofac、Unity、spring.net等。一般常用的還是自帶和Autofac,今天我們來簡單介紹下Autofac。

2、案例實戰

建立一個Asp.Net Core Api項目:AutofacDemo

【案例分享】Asp.net Core內建Autofac

輕按兩下項目檔案引入依賴:

<ItemGroup>
		<PackageReference Include="Autofac" Version="6.2.0" />
		<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
	</ItemGroup>           

在Startup檔案中添加命名空間:

using Autofac;
using Autofac.Features.AttributeFilters;           

在Program中替換服務提供商:

.UseServiceProviderFactory(new AutofacServiceProviderFactory())           
【案例分享】Asp.net Core內建Autofac

建立測試服務:IProductService、IProductService,ProductController

public interface IProductService
    {
        public string Get();
        public List<string> GetList();
    }

   public class ProductService : IProductService
    {
        public string Get()
        {
            return "優質蔬菜";
        }

        public List<string> GetList()
        {
            return new List<string>() { "優質農場品", "優質大豆" };
        }
    }

[Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductService productService;
        public ProductController(IProductService productService)
        {
            this.productService = productService;
        }

        [HttpGet("Get")]
        public string Get()
        {
            return productService.Get();
        }

        [HttpGet("GetList")]
        public List<string> GetList()
        {
            return productService.GetList();
        }
    }           

注入依賴,需要在Startup中增加服務配置方法:

public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterType<ProductService>().As<IProductService>().SingleInstance();
        }           

啟動項目,輸入路由:

https://localhost:{你的端口号}/api/product/get           
【案例分享】Asp.net Core內建Autofac

簡單的使用已經達到目的,如果你想更友善的使用,可以對依賴注入進行封裝,通過子產品或者掃描程式集來實作集中注入。

繼續閱讀