gpt4 book ai didi

c# - 使用结构图根据消费者解析不同的装饰实例

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:35 24 4
gpt4 key购买 nike

该应用程序是一个 ASP.NET MVC webapp,由存储库构建,前端是用于后端的具体服务层。我使用结构图 3 作为 IoC 来为每个具体服务注入(inject)存储库。对于日志记录/缓存等。我使用装饰的存储库,它也是用结构图设置的。

该应用程序具有公开和非公开部分。非公开部分是一些 super 用户登录并创建和更新内容的地方。公共(public)部分由 http 处理程序组成,公开在网络上,处理对应用程序的所有请求的 99.99%。

当实例在 http 处理程序中解析但不在应用程序的其余部分中解析时,我想配置结构映射以使用缓存装饰存储库。我还想在 http 处理程序中解析时向服务注入(inject)不同的记录器。

这是否可能根据消费者获得相同接口(interface)实现的不同设置?

public interface IEntityRepository<IEntity>
{
}

public class ContentService : IEntityService
{
public ContentService(IEntityRepository<Content> repoistory, ILogger logger)
{

}
}

最佳答案

请注意,此解决方案不提供您正在寻找的功能 - 传递到 DecorateAllWith 中的委托(delegate)仅针对已解析的每种类型调用一次。


DecorateAllWith 方法有一个重载,可用于分析正在创建的类型并进行相应的过滤

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

});
registry.For(typeof(IEntityRepository<>))
.DecorateAllWith(typeof(CachingDecorator<>), instance => false);
});

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

Assert.IsNotType<CachingDecorator<Entity1>>(result);
}

关于c# - 使用结构图根据消费者解析不同的装饰实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25178491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com