如何注册使用TinyIOC通用接口 [英] How to register a generic interface using TinyIOC

查看:931
本文介绍了如何注册使用TinyIOC通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a generic interface and a generic implementation. How do I register all usages?

具体而言,我有以下的(减少为简单起见):

Specifically, I have the following (reduced for simplicity):

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
{
    ...
}

我是否需要登记所有实现一个接一个,像这样:

Do I need to register all implementations one by one, like so:

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

或者是有一个较短的方式?

Or is there a shorter way?

推荐答案

正如我的评论,TinyIoC在打开泛型的分辨率中的错误 - 它不留解决实例与不同类型的参数分开,并作为所有登记都隐含有 .AsSingleton()默认情况下,它总是返回已解决了所有后续的解析请求的一般类型的第一个实例。做

As mentioned in my comment, TinyIoC has a bug in the resolution of Open Generics - it doesn't keep the resolved instances with different type parameters apart, and as all registrations are implicitly done with .AsSingleton() by default, it always returns the first instance of the generic type that was resolved for all subsequent resolution requests.

由于这个原因,下面不工作:

Due to this, the following doesn't work:

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

然而,有一种变通方法, - 使登记短暂:

There is a workaround, however - make the registration transient:

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

这将创建一个新的实例为每个解析请求,并好好孝敬类型参数。这种方法的缺点是,你还每次请求接口与具有previously被解决一个类型参数时获得一个新的实例。

This will create a new instance for each resolution request and properly honor the type parameter. The downside of this is that you also get a new instance each time you request the interface with a type parameter that has previously been resolved.

修改

确认。开放式泛型决议并使用 SingletonFactory ,一旦它已经建立了一个实例,将始终返回,对于随后的决议。它不知道也不关心泛型。为此正常工作,一个 GenericSingletonFactory 将需要不只是保持一个实例,而是由具体类型键控字典来加以解决。

Confirmed. Open Generics resolution does use the SingletonFactory that once it has created an instance will always return that for subsequent resolutions. It doesn't know or care about Generics. For this to work properly, a GenericSingletonFactory would be required that does not only keep a single instance but a dictionary keyed by the concrete type to be resolved.

好吧,这甚至不是那么难解决。我只是不明白还不够了解尚待确定它确实是正确的。

Alright, that wasn't even that hard to fix. I just don't understand enough about it yet to be sure that it's really all correct.

这篇关于如何注册使用TinyIOC通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆