Structuremap3 DecorateAllWith

时间:2014-08-05 08:16:52

标签: c# decorator structuremap3

我一直在努力让DecorateAllWith在通用接口上工作。我已经在这里阅读了一些帖子,他们使用拦截器解决了这些问题,但他们似乎使用的是较旧的结构图版本,并且它看起来并不像一个干净的"溶液

我真的需要一些帮助来使用结构图3

我有一个通用的存储库,我想用日志记录和缓存来装饰

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

我有大约20个继承IEntityRepository的接口。示例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;
    }
}

还有其他IoC容器更适合我想要完成的任务吗?

编辑:有没有办法装饰从IEntityRepository继承的所有接口

1 个答案:

答案 0 :(得分: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);
}

要回答您的第二个问题,我个人使用(并参与)Simple Injector - 它是可用的fastest容器之一,全面支持generics并提供一些强大的diagnostic {3}}服务。

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);
}