【问题标题】:Resolve dependencies from inherited classes with Autofac使用 Autofac 解决继承类的依赖关系
【发布时间】:2015-10-19 16:01:26
【问题描述】:

首先,让我提供一些示例代码:

public abstract class BaseEntity { }
public class MyEntity : BaseEntity { }
public class MyCustomEntity : BaseEntity { }

public interface IStore<TEntity> where TEntity : BaseEntity { }
public class BaseStore<TEntity> : IStore<TEntity> where TEntity : BaseEntity { }
public class MyCustomEntityStore : BaseStore<MyEntity> { }

所以基本上我有一个抽象实体和两个派生类型。我创建了一个存储库类,它隐藏了 BaseEntity 周围的所有基本内容(例如填充“LastModifiedBy”属性)。但是对于某些情况,我需要特定的行为来保存实体,所以我需要从BaseStore 派生,并在MyCustomEntityStore 中实现自定义行为。到目前为止,这很容易。

问题是我想使用 Autofac 来解决我的应用程序中的依赖关系。我的目标是这样做:

public class SomeClass {
    private readonly IStore<MyEntity> MyEntityStore;
    private readonly IStore<MyCustomEntity> MyCustomEntityStore;

    public SomeClass(IStore<MyEntity> mes, IStore<MyCustomEntity> mces)
    {
        MyEntityStore = mes;
        MyCustomEntityStore = mces;
    }
}

我想将BaseStore&lt;MyEntity&gt; 的实例注入IStore&lt;MyEntity&gt;MyCustomEntityStoreIStore&lt;MyCustomEntity&gt;。这适用于MyCustomEntityStore(它有一个从基本存储派生的具体实现),但我不想创建空类只是为了继承BaseStore&lt;MyEntity&gt;。我像这样注册了我的组件:

builder.RegisterAssemblyTypes(Assembly.Load("Project.Data")).Where(t => t.Name.EndsWith("Store")).AsImplementedInterfaces().InstancePerRequest();

虽然这些实例可以代替这些接口,但Autofac无法解析IStore&lt;MyEntity&gt;

感谢大家的帮助!

【问题讨论】:

    标签: c# dependency-injection autofac


    【解决方案1】:

    我设法解决了这个注册的问题:

    builder.RegisterGeneric(typeof(BaseStore<>))
           .As(typeof(IStore<>))
           .InstancePerRequest();
    builder.RegisterAssemblyTypes(Assembly.Load("Project.Data"))
           .Where(t => t.Name.EndsWith("Store"))
           .AsImplementedInterfaces()
           .InstancePerRequest();
    

    任何人都可以确认,这是正确的方法吗?

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多