문제

I have a repository layer where these take DbContext into the constructor. I'm using InCallScope but the dbcontext instance seems to be different in the repositories. Here is the code:

Bind<DbContext>().ToMethod(ctx =>new TaCertoEntities()).InCallScope();
Bind<IContratacaoRepository>().To<ContratacaoRepository>();

 using (var context = Ioc.Container.Get<DbContext>())
        {
            Ioc.Container.Get<IContratacaoRepository>().Insert(xxx);

            context.Save();
        }

What i'm i doing wrong?

Thanks!

도움이 되었습니까?

해결책

Everytime you ask the Kernel for a service using this IoC.Container.Get<T> you will get a different instance if you are using InCallScope(). This is what you are doing wrong.

You should avoid using this Service Locator anti-pattern. This symptom you are facing is clearly one side-effect of this anti-pattern: You don't know where your Composition Root is.

Without determining your composition root, the use of scopes is renderes pratically useless. When asking for new instances via Service Locator everytime you need a dependency, the kernel can't guess how to resolve the scopes and you are bound to run into this kind of issue.

If you are using a MVC / WebAPI application, your controller surely will be the activation point for your object graph, since it's dependencies will be injected. But you must leave that to Ninject do that work for you.

The Nuget package Ninject.MVC3 automatically configures your web application for injection. Or, if you are not using a web application, please provide some more sample code so I can help you determine what your composition root is and how the scopes can help you solve the issue you are facing.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top