c# - 如何使用 TinyIOC 注册通用接口(interface)

标签 c# .net generics inversion-of-control tinyioc

假设我有一个通用接口(interface)和一个通用实现。我如何注册所有用途?

具体来说,我有以下内容(为简单起见减少了):

public interface IRepository<T> where T : TableEntity
{
    T GetById(string partitionKey, string rowKey);
    void Insert(T entity);
    void Update(T entity);
    void Update(string partitionKey, string rowKey, Action<T> updateAction);
    void Delete(T entity);
    IQueryable<T> Table { get; }
}


public class AzureRepository<T> : IRepository<T> where T : TableEntity
{
    ...
}

我是否需要像这样一一注册所有实现:

container.Register<IRepository<Entity1>, AzureRepository<Entity1>>();
container.Register<IRepository<Entity2>, AzureRepository<Entity2>>();
container.Register<IRepository<Entity3>, AzureRepository<Entity3>>();
...

或者有更短的路吗?

最佳答案

正如我在评论中提到的,TinyIoC 在 Open Generics 的解析中有一个错误 - 它不会将具有不同类型参数的已解析实例分开,并且因为所有注册都是通过 .AsSingleton()< 隐式完成的 默认情况下,它始终返回为所有后续解析请求解析的泛型类型的第一个实例。

因此,以下内容不起作用:

container.Register(typeof(IRepository<>), typeof(AzureRepository<>));

不过,有一个解决方法 - 使注册成为 transient :

container.Register(typeof(IRepository<>), typeof(AzureRepository<>)).AsMultiInstance();

这将为每个解析请求创建一个新实例,并正确地遵循类型参数。这样做的缺点是,每次使用先前已解析的类型参数请求接口(interface)时,您也会获得一个新实例。

编辑

确认。 Open Generics 解析确实使用 SingletonFactory,一旦它创建了一个实例,它将始终为后续解析返回该实例。它不知道也不关心泛型。为了使其正常工作,需要一个 GenericSingletonFactory,它不仅保留单个实例,而且还保留由要解析的具体类型键入的字典。

好吧,这甚至没有那么难解决。我只是对它还不够了解,无法确定它真的是正确的。

关于c# - 如何使用 TinyIOC 注册通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15450518/

相关文章:

c# - 在调试期间在 Visual Studio 中自动附加到子进程

java - 我无法在代码中实例化 Integer 类的对象 (Java)

java - 迭代 LinkedHashMap 显示编译错误

c# - 如何使用获取所有登录用户的列表

c# - 使用 PropertyInfo.GetValue()

c# - 创建应用程序的 Hook ?

c# - 直接从 Dictionary<> 获取 KeyValuePair<>

c# - Ms-Chart 标签格式问题

C# 并行运行任务并将每个任务与输入关联

c# - 在c#中查找已编译类的源文件