StructureMap构造函数的参数范围函数、范围、参数、StructureMap

2023-09-06 22:16:40 作者:玩心卻動情。

我一直在寻找了一整天,不明白这一点。我希望它一直没有问过。

I've been searching all day and can't figure this out. I hope it hasn't been asked before.

ObjectFactory.Initialize(
    x =>
        {
            x.For(typeof (IRepository<>))
             .Use(typeof(Repository<>))
             .CtorDependency<DbContext>("dbContext")
             .Is(new DbContext());
        }
    );

我需要structuremap使用'的DbContext它创建的每个资源库的新实例时的新实例。现在,我相信这是再利用的DbContext及其导致的问题。我相信这只是重用的DbContext因为我已经尝试设置的信息库的生命周期PerRequest具有相同的结果。任何帮助是极大的AP preciated。

I need structuremap to use a new instance of 'DbContext' each time it creates a new instance of 'Repository'. Right now I believe it is reusing 'DbContext' and its causing issues. I believe it is reusing only 'DbContext' because I have tried setting the lifecycle on 'Repository' to PerRequest with the same result. Any help is greatly appreciated.

我是新来StructureMap和依赖注入,所以我可能是不正确的我的分析。

I'm new to StructureMap and Dependency Injection so I may be incorrect in my analysis.

更新

@PHeiberg非常感谢你的回答。它响了门铃我记得看到了拉姆达EX pression开始()我从来没有见过的。我是超级兴奋,这是它。 我想你的code逐字记录和它无法解析构造函数,所以我改成了这一点。

@PHeiberg thank you so much for your answer. It rang a bell I remember seeing that lambda expression starting with '()' that I hadn't seen before. I was super excited that this was it. I tried your code verbatim and it can't resolve Ctor so I changed it to this.

                        x.For(typeof(IRepository<>))
                      .HttpContextScoped()
                      .Use(typeof(Repository<>))
                      .CtorDependency<DbContext>("dbContext")
                      .Is(() => new DbContext());       

和我收到以下编译错误

无法解析法'是(的Lamda exression),候选人分别是:StructureMap.Pipeline.ConfiguredInstance IS(对象)(类ChildInstanceEx pression)StructureMap.Pipeline.ConfiguredInstance是(StructureMap.Pipeline.Instance)(在课堂上ChildInstanceEx pression)。

"Cannot resolve method 'Is(Lamda exression)', candidates are: StructureMap.Pipeline.ConfiguredInstance Is(object) (in class ChildInstanceExpression) StructureMap.Pipeline.ConfiguredInstance Is(StructureMap.Pipeline.Instance) (in class ChildInstanceExpression).

我已经看到了这条消息之前,我还记得,这导致了我尝试注册我的DbContext类型,虽然我不知道你能不能也不会,如果我是做正确的,说x.For(具体类型)。使用(具体类型) 。

I have seen this message before I remember and it resulted in my trying to register my dbContext Type although I dont know if you can nor if I was doing correctly, say x.For(concrete type).Use(concrete type).

推荐答案

使用

x.For<IRepository>()
    .HttpContextScoped()
    .Use<Repository>()
    .CtorDependency<DbContext>("dbContext")
    .Is(ctx => new DbContext());

。是()接受一个类型的函数功能和LT; IContext,T&GT;