我一直在努力让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继承的所有接口?
发布于 2014-08-05 10:14:44
下面是一个回答你第一个问题的工作例子
[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);
}为了回答您的第二个问题,我个人使用(并贡献了) 简单喷射器 --它是可用的最快容器之一,对仿制药提供了全面的支持,并提供了一些强大的诊断性服务。
简单注入器中的注册如下所示:
[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);
}https://stackoverflow.com/questions/25134096
复制相似问题