我一直在努力让DecorateAllWith上通用接口的工作。 他们解决了使用拦截器,但他们似乎可以用旧的结构图版本,它似乎并不像一个“干净”的解决方案是我在这里读了一些文章。
我真的需要一些帮助来把它与结构图3工作
我有一个通用的存储库,我想用两个记录和缓存来装饰
public interface IEntityRepository<T> where T : Entities.IEntity
{
}
我有大约20个接口继承IEntityRepository。 实施例亩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继承所有接口
下面是回答你的第一个问题的工作示例
[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);
}