Asp.net Core AutoFac根据程序集实现依赖注入

一、创建一个专门用于依赖注入的接口(IAutoInject), 所有的服务接口皆继承于此接口

namespace DDD.Domain
{
    public interface IAutoInject
    {
    }
}

  

二、添加服务接口,需要继承IAutoInject

namespace DDD.Domain.Product.Inter
{
    public interface IProductTypeService : IAutoInject
    {
        int Add(ProductType entity);
    }
}

三、添加服务实现类,继承服务接口IProductTypeService

 
namespace DDD.Domain.Product.Impl
{
    public class ProductTypeService: DBBase , IProductTypeService
    {
        public int Add(ProductType entity)
        {
           return db.Insertable(entity).ExecuteCommand();
        }
    }
}

四、添加依赖注入类

 
namespace CoreTest
{
    public class AutoFacIoc
    {
        public static IContainer Injection(IServiceCollection services)
        {
            var builder = new ContainerBuilder();
            //InstancePerLifetimeScope:同一个Lifetime生成的对象是同一个实例
            //SingleInstance:单例模式,每次调用,都会使用同一个实例化的对象;每次都用同一个对象;
            //InstancePerDependency:默认模式,每次调用,都会重新实例化对象;每次请求都创建一个新的对象;
 
            //获取IAutoInject的类型
            var baseTypeDomain = typeof(DDD.Domain.IAutoInject);
            //获取所有需要依赖注入的程序集
            //DDD.Domain是服务所在程序集命名空间  
            Assembly assembliesDomain = Assembly.Load("DDD.Domain");
            //自动注册接口
            builder.RegisterAssemblyTypes(assembliesDomain)
                .Where(b => b.GetInterfaces().Any(c => c == baseTypeDomain && b != baseTypeDomain))
                .AsImplementedInterfaces()
                .SingleInstance(); //见上方说明
 
            builder.Populate(services);
            return builder.Build();
        }
    }
}

五、再Startup.cs中调用

说明: 需要修改ConfigureServices方法的返回值为 IServiceProvider ; 添加ApplicationContainer 属性

 public IContainer ApplicationContainer { get; private set; }
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
 
     this.ApplicationContainer = AutoFacIoc.Injection(services);
     return new AutofacServiceProvider(this.ApplicationContainer);
  }

六、根据构造函数进行注入

namespace CoreTest.Controllers
{
public class ProductTypeController : Controller
{
IProductTypeService productTypeService;
public ProductTypeController(IProductTypeService _productTypeService)
{
this.productTypeService = _productTypeService;
}
public IActionResult Add()
{
ProductType entity = new ProductType()
{
CreateBy = "",
CreateTime = DateTime.Now
};
int re = productTypeService.Add(entity);

re += productApp.AddProductType(entity);
return Json(re);
}
}
}

本文转自:

https://blog.csdn.net/qq_26900081/article/details/82984010

原文地址:https://www.cnblogs.com/xiaoguli/p/11259466.html