微软默认的容器,不支持命名选项,同一接口,多个实现。 就不支持了。
配置core 支持Autofac 容器
csharp
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace WebApplication13
{
public interface IMyService
{
string GetData();
}
public class MyService : IMyService
{
public string GetData()
{
return "Data from MyService---MyService";
}
}
public class MyService2 : IMyService
{
public string GetData()
{
return "2222 from MyService---MyService2";
}
}
public class MyApplicationModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyService>().As<IMyService>();
}
}
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// 在这里添加内置DI容器的服务配置
// 例如,
builder.Services.AddRazorPages();
// 使用Autofac作为服务提供商
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
// 在这里向Autofac容器注册服务 此处使用模块方式注入
containerBuilder.RegisterModule<MyApplicationModule>();
});
Add services to the container.
//builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
}
}
}
autofac 支持 命名 、key
csharp
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace WebApplication13
{
public interface IMyService
{
string GetData();
}
public class MyService : IMyService
{
public string GetData()
{
return "Data from MyService---MyService";
}
}
public class MyService2 : IMyService
{
public string GetData()
{
return "2222 from MyService---MyService2";
}
}
public class MyApplicationModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyService>().As<IMyService>();
builder.RegisterType<MyService>().As<IMyService>().Named<IMyService>(typeof(MyService).Name);
//builder.RegisterType<MyService>().As<IMyService>().Keyed<IMyService>(typeof(MyService).Name);
builder.RegisterType<MyService2>().As<IMyService>().Named<IMyService>(nameof(MyService2));
}
}
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// 在这里添加内置DI容器的服务配置
// 例如,
builder.Services.AddRazorPages();
// 使用Autofac作为服务提供商
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
// 在这里向Autofac容器注册服务 此处使用模块方式注入
containerBuilder.RegisterModule<MyApplicationModule>();
});
Add services to the container.
//builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
}
}
}