文章目录
依赖注入与IOC
IOC
依赖注入DI
1、继承接口并实现构造方法
public class UserService : IUserService
{
private IUserRepository _userService ;
public UserService(IUserRepository userService)
{
_userService = userService;
}
}
2、在program里加上
builder.Services.AddTransient<IUserRepository, UserRepository>();
builder.Services.AddTransient<IUserService, UserService>();
3、Controller层使用
public class UserController : ControllerBase
{
private readonly IUserService _userService ;
public UserController(IUserService userService)
{
_userService = userService;
}
}
Autofac轻量容器的使用
1、安装Nuget包Autofac.Extensions.DependencyInjection
和Autofac.Extras.DynamicProxy
2、使用程序集注册,通过Model注册(这里只列这一种Auto官方文档Assembly Scanning — Autofac 7.0.0 documentation)
**创建Model类 **
using Autofac;
using Blog.Core.IServices;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using System.Reflection;
using System.Runtime.Loader;
namespace Blog.Core.Configuration.AutoModule
{
public class ServiceModel: Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
// 自动对集成 IDependency 接口的类进行注册
Type baseType = typeof(IUserService);
var compilationLibrary = DependencyContext.Default.CompileLibraries.Where(x => !x.Serviceable && x.Type == "project").ToList();
List<Assembly> assemblyList = new List<Assembly>();
foreach (var _compilation in compilationLibrary)
{
try
{
assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
}
catch (Exception ex)
{
Console.WriteLine(_compilation.Name + ex.Message);
}
}
builder.RegisterAssemblyTypes(assemblyList.ToArray()).Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
.AsSelf()
.AsImplementedInterfaces()
.PropertiesAutowired()
.InstancePerLifetimeScope();
var controllersTypesInAssembly = typeof(Program).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
}
}
}
**在program.cs中解析Model **
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(i => i.RegisterModule<ServiceModel>());
builder.Services.AddControllers().AddControllersAsServices();
在Controller中使用
public class UserController : ControllerBase
{
private readonly IUserService _userService ;
public UserController(IUserService userService)
{
_userService = userService;
}
}