【发布时间】:2018-03-23 13:29:09
【问题描述】:
我正在使用ASP.NET Core 2.0 和Microsoft.Extensions.DependencyInjection。我有几个类我不想指定它的实现或者我不需要指定。
例如:
public interface IMyService
{
void WriteSomething();
}
public class MyService : IMyService
{
private readonly MyObject myObject;
public MyService(MyObject myObject)
{
this.myObject = myObject;
}
public void WriteSomething()
{
this.myObject.Write();
}
}
public interface IOther
{
string GetName();
}
public class Other : IOther
{
public string GetName()
{
return "james bond";
}
}
public class MyObject
{
private readonly IOther other;
public MyObject(IOther other)
{
this.other = other;
}
public void Write()
{
Console.WriteLine(string.Concat("hi ", this.other.GetName()));
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<IOther, Other>();
services.AddScoped<IMyService, MyService>();
...
}
}
我只想指定IMyToolGeneral 和MyToolGeneral 和IOther 和Other,但MyObject 不是,因为我有很多这样的类(验证器、助手......)和我不需要指定这些。
如何在ASP.NET Core 2.0 中做到这一点?
编辑
我需要ASP.NET Core 2.0 DI 可以注入 MyObject 的实例,而无需在 DI 配置中指定它。 MyObject 没有基类的契约(接口),其构造函数中的所有参数都在 DI 配置中指定。
编辑二 我重写了类并在 Unity 中包含了一个示例(有效)和 MS DI 中的相同示例(无效)
统一示例(工作)
class Program
{
static void Main(string[] args)
{
var container = UnityConfig();
var service = container.Resolve<IMyService>();
service.WriteSomething();
Console.ReadKey();
}
static UnityContainer UnityConfig()
{
var container = new UnityContainer();
container.RegisterType<IMyService, MyService>();
container.RegisterType<IOther, Other>();
return container;
}
}
MS DI(不工作) 未处理的异常:System.InvalidOperationException:尝试激活“ConsoleDI.MyService”时无法解析“ConsoleDI.MyObject”类型的服务。
class Program
{
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddTransient<IMyService, MyService>()
.AddTransient<IOther, Other>()
.BuildServiceProvider();
var service = serviceProvider.GetService<IMyService>();
service.WriteSomething();
Console.ReadKey();
}
}
【问题讨论】:
-
也许
services.AddTransient<MyObject >(); -
@Kirk Ready,我提供了更多细节
-
@IvanMilosavljevic 我需要避免这种情况。
-
@IvanMilosavljevic 是的,我知道,但我需要避免这种情况。在 Unity 中可以做到。
-
您是否严格使用 Microsoft DI?有autofac property injection。
标签: c# asp.net dependency-injection asp.net-core asp.net-core-2.0