1、Microsoft.Extensions.DependencyInjection
这是.Net Core框架本身内置集成的,我们只需引入Microsoft.Extensions.DependencyInjection,就可以直接使用。
using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
var builder = WebApplication.CreateBuilder();
builder.Services.AddRazorPages();
builder.Services.AddScoped<IMyDependency, MyDependency>();
var app = builder.Build();
2、AutoFac
var builder = WebApplication.CreateBuilder();
// 注册组件
builder.RegisterType<MyService>().As<IMyService>();
builder.RegisterType<AnotherService>().As<IAnotherService>().InstancePerLifetimeScope();
// 构建容器
var app= builder.Build();
// 解析服务
var myService = app.Resolve<IMyService>();
3、Ninject
public class WarriorModule : NinjectModule
{
public override void Load()
{
this.Bind<IWeapon>().To<Sword>();
}
}
4、SimpleInjector
https://github.com/simpleinjector/SimpleInjector
Star:1.2K
// 1. 创建容器
var container = new Container();
// 2. 配置容器(注册服务)
container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Transient);
container.Register<ILogger, MailLogger>(Lifestyle.Singleton);
container.Register<UserController>();
// 3. 验证容器配置:
container.Verify();
// 4. 注册容器为MVC的依赖解析器
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
5、Windsor
https://github.com/castleproject/Windsor
Star:1.5K
// 创建容器
var container = new WindsorContainer();
// 添加和配置组件
container.Install(FromAssembly.This());
// 解析并配置根组件及其所有依赖项
var king = container.Resolve<IKing>();
king.RuleTheCastle();
// 清理容器,应用程序退出
container.Dispose();