gpt4 book ai didi

StructureMap 获取请求的类型

转载 作者:行者123 更新时间:2023-12-02 00:37:42 24 4
gpt4 key购买 nike

是否可以在配置 StructureMap 容器时将请求类型作为参数传递。

例如:

            container.Configure(x => {
x.For<ILogger>().Use(new TestLogger(log.Add, requestingType));
});

其中请求类型是消费对象的类型:

public class SomeClass
{
private readonly ILogger logger;
public SomeClass(ILogger logger)
{
this.logger = logger;
}
}

因此传递给记录器的类型将是 SomeNamespace.SomeClass。

谢谢,本

最佳答案

您可以使用 StructureMap 的 IContext 轻松访问请求的类型。

ObjectFactory.Configure(
x => {
x.For<ILogger>().Use( context => new TestLogger( context.ParentType ) );
} );

在上面的语句中,context.ParentType 返回由 StructureMap 创建的类型。

Jeremy Miller 也在一篇博文中介绍了这个主题。该文章使用了过时的语法,但它仍然相关:http://codebetter.com/jeremymiller/2009/01/15/using-the-build-session-in-structuremap/

如果您想检查 IContext 中的所有可用属性,您可以使用匿名函数并在返回行上设置断点,如下所示:

ObjectFactory.Configure(
x => {
x.For<ILogger>()
.Use( context =>
{
// Set breakpoint here and inspect the context
return new TestLogger( context.ParentType );
} );
} );

更新:

确保使用 .AlwaysUnique() (相当于旧语法 .CacheBy( InstanceScope.Unique ) )否则 StructureMap 将缓存 ILogger 的第一个请求,这将导致原始记录器被注入(inject)所有后续在单个 GetInstance() 调用期间对 ILogger 的请求。

如果您有嵌套的类,每个类都需要一个 ILogger,那么这很容易发生,因此对 ObjectFactory.GetInstance< ISomeClass >() 的请求将导致为层次结构中最深的类创建一个 ILogger,然后所有其他类将收到ILogger 的同一个实例很可能是您希望发生的事情。

因此,考虑到此更新和 Ben 的提示,这里有一个更好的解决方案:

x.For<ILogger>()
.AlwaysUnique()
.Use( c => new TestLogger( c.ParentType ?? c.BuildStack.Current.ConcreteType ) );

关于StructureMap 获取请求的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944326/

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