【发布时间】:2019-10-22 00:38:37
【问题描述】:
我有一个接受 Type 作为构造函数参数的基类,以及从该基类继承的两个派生类。我也有那个基类的接口,我注入它以在其他地方使用。
当我调用基方法“FormatValue”,将不同类型作为参数传递时,我总是得到相同的结果(它调用其中一个类中的方法,忽略我的类型参数)。
我做错了什么?
public interface IFormatService
{
string FormatValue(object value);
}
public abstract class FormatService : IFormatService
{
protected FormatService(Type type)
{ }
public abstract string FormatValue(object value);
}
public static class Program
{
private static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddSingleton<IFormatService, CurrencyFormat>()
.AddSingleton<IFormatService, DateTimeFormat>()
.BuildServiceProvider();
var formatService = serviceProvider.GetService<IFormatService>();
Console.WriteLine(formatService.FormatValue(DateTime.Now));
Console.WriteLine(formatService.FormatValue(200));
Console.ReadLine();
}
}
public class CurrencyFormat : FormatService
{
public CurrencyFormat() : base(typeof(decimal))
{
}
public override string FormatValue(object value) => "CurrencyFormatter";
}
public class DateTimeFormat : FormatService
{
public DateTimeFormat() : base(typeof(DateTime))
{
}
public override string FormatValue(object value) => "DateTimeFormatter";
}
当前结果:
DateTimeFormatter
DateTimeFormatter
预期结果:
DateTimeFormatter
CurrencyFormatter
【问题讨论】:
-
您的第二次注册
.AddSingleton<IFormatService, DateTimeFormat>()覆盖了前一次,您应该使IFormatService通用IFormatService<T>正常工作。 -
谢谢!但是如何注册一个通用接口呢?作为瞬态?以及如何获得服务,因为我为我拥有的每种类型声明了每一种服务?
-
你可以像这样
.AddSingleton<IFormatService<DateTime>, DateTimeFormat>()注册单身。 -
但是我必须为我拥有的每种类型声明一个服务?喜欢
var datetimeFormatService = serviceProvider.GetService<IFormatService<DateTime>>(); var currencyFormatService = serviceProvider.GetService<IFormatService<decimal>>();
标签: c# oop dependency-injection abstract-class derived-class