Autofac: register an instance of type A, after type A is already registered as type

109 Views Asked by At

I have a PortalEntities class whick extends DbContext.

I have a EFGenRepo class with a private prop context of type PortalEntites. This EFGenRepo class has a constructor:

public EFGenRepo(PortalEntities entities) { this.context = entities; }

Now I have a ClientManager class which has an instance of the EFGenRepo called repo. Remember since the context prop in repo is private I cannot acces it!


Now I have this line of code inside one of the methods of ClientManager:

FKEntityList.Add(new PortalEntities().Set<FKEntity>().Find(FKEntity_id));

And this is where I get an error message:

  • The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

The FKEntityList is build using a find method of repo which itself uses the context prop in EFGenRepo.


I use autofac and registered PortalEntities like this, so it can be injected in a controller: cb.RegisterType<PortalEntities>().AsSelf().InstancePerRequest();

However in my method I use new PortalEntites() and it must be registered too somehow with the Type PortalEntities. But I can not get it working. I already tried the code below:

cb.RegisterInstance(new PortalEntities()).AsSelf().SingleInstance();

Does somebody know how to setup?

1

There are 1 best solutions below

2
On

In your ClientManager class, you should not create (and even use) PortalEntities class. Move database query logic into your repository, which already has PortalEntities instance.