1

私は、汎用インターフェイスで DecorateAllWith を動作させるのに苦労しています。ここで、インターセプターを使用して解決したいくつかの投稿を読みましたが、古い構造マップ バージョンを使用しているようで、「クリーンな」ソリューションのようには見えません。

構造マップ3で動作させるには、本当に助けが必要です

ロギングとキャッシングの両方で装飾したい汎用リポジトリがあります

public interface IEntityRepository<T> where T : Entities.IEntity
{
}

IEntityRepository を継承する約 20 のインターフェイスがあります。例 mu UserRepository

public interface IUserEntityRepository : IEntityRepository<User>
{
}

そして、IEntityRepository のすべてのインスタンスを装飾したいロギング デコレータの具象型があります。

public class LoggingEntityRepository<T> : IEntityRepository<T> where T : Entities.IEntity
{
    private readonly IEntityRepository<T> _repositoryDecorated;

    public LoggingEntityRepository(IEntityRepository<T> repositoryDecorated)
    {
        _repositoryDecorated = repositoryDecorated;
    }
}

または、私が達成しようとしていることに適した他の IC コンテナーはありますか?

編集: IEntityRepository から継承するすべてのインターフェイスを装飾する方法はありますか

4

1 に答える 1

0

最初の質問に答える実際の例を次に示します

[Fact]
public void DecorateAllWith_AppliedToGenericType_IsReturned()
{
    var container = new Container(registry =>
    {
        registry.Scan(x =>
        {
            x.TheCallingAssembly();
            x.ConnectImplementationsToTypesClosing(typeof(IEntityRepository<>));

        });

        registry.For(typeof(IEntityRepository<>))
            .DecorateAllWith(typeof(LoggingEntityRepository<>));
    });

    var result = container.GetInstance<IEntityRepository<Entity1>>();

    Assert.IsType<LoggingEntityRepository<Entity1>>(result);
}

2 番目の質問に答えるために、私は個人的にSimple Injectorを使用 (および貢献) しています。これは利用可能な最速のコンテナーの 1 つであり、ジェネリックを包括的にサポートし、いくつかの強力な診断サービスを提供します。

Simple Injector での登録は次のようになります。

[Fact]
public void RegisterDecorator_AppliedToGenericType_IsReturned()
{
    var container = new SimpleInjector.Container();

    container.RegisterManyForOpenGeneric(
        typeof(IEntityRepository<>), 
        typeof(IEntityRepository<>).Assembly);

    container.RegisterDecorator(
        typeof(IEntityRepository<>), 
        typeof(LoggingEntityRepository<>));

    var result = container.GetInstance<IEntityRepository<Entity1>>();

    Assert.IsType<LoggingEntityRepository<Entity1>>(result);
}
于 2014-08-05T10:14:44.260 に答える