【问题标题】:TornLifestyle simple injectorTornLifestyle 简单注射器
【发布时间】:2016-04-26 19:47:14
【问题描述】:

我已经定义了一个这样的通用接口:

public interface IPlanManagmentRepository<TEntity> where TEntity:class

当我定义这样的具体实现时:

public class ProviderPlanManagementRepo : IPlanManagmentRepository<Provider>

一切都通过像这样注册接口来工作:

container.Register(typeof(IPlanManagmentRepository<>), 
    new [] { typeof(IPlanManagmentRepository<>).Assembly}, 
    Lifestyle.Scoped);

但是,如果这个类也处理更多的东西,我添加了一个额外的接口:

public interface IProviderPlanManagementRepo
{
    void doSomethingSpecificToProviderHere();
}
public class ProviderPlanManagementRepo : IProviderPlanManagementRepo,
    IPlanManagmentRepository<Provider>
{
}

然后我得到这个错误:

-[Torn Lifestyle] IPlanManagmentRepository 的注册映射到与 IProviderPlanManagementRepo 的注册相同的实现和生活方式。它们都映射到 ProviderPlanManagementRepo

我也尝试在 IProviderPlanManagementRepo 中继承 IPlanManagmentRepository,但得到了同样的错误。

这个类应该只处理泛型接口的实现吗? 还是可以用简单的注射器来完成这个?

【问题讨论】:

    标签: c# generics simple-injector


    【解决方案1】:

    更新:

    随着 Simple Injector 4 的引入,在大多数情况下,容器将阻止为同一具体类型创建多个注册实例。因此,Torn Lifestyles 警告类型应该非常少见。只有当自定义生活方式绕过 Lifestyle.CreateRegistration 重载的缓存行为时,才会发生撕裂的生活方式。


    您的问题与work itemthis discussion 有关。通常,可以修复被破坏的生活方式as follows,但是当使用批量注册注册具有多个不相关接口的类型时,Simple Injector 3.1 使得修复违规变得异常困难。这是我们将在即将发布的小版本之一中解决的问题。

    我现在可以推荐的最简单的解决方法是让您的IPlanManagmentRepository&lt;T&gt; 注册成为暂时的。您应该能够使它们瞬态,因为您的组件应该是不可变的。所以通常只有DbContext 应该是Scoped,但您甚至可能不想将DbContext 注入到您的存储库中,因为DbContext 是运行时数据,而运行时数据应该是not be injected into the components of your object graph

    【讨论】:

    • 谢谢@Steven,正如你提到的我的 DbContext 是作用域的,我尝试了你的建议,即使 DbContext 是作用域的,它也有效,但我想知道如果我使用的是 3,这是否会有一些潜在的问题包括上面提到的一个(瞬态的)的存储库,所有 3 个都将共享相同的 DbContext 吗?这很重要,因为它们都需要共享同一个事务。
    • @danif430:是的,他们将共享同一个实例。试试看。
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多