简体   繁体   中英

Autofac copy registrations from one container to another

We are trying to improve the performance of our unit test by creating common initialization for all tests in TestBaseClass. So far we were able to resolve it to some degree. All of our test classes resolve directly from container (I think it is a better idea to resolve from lifetimescope but it's probably too late for a change like this). The problem with performance is that in every test we might override some registrations using builder.Update(C); (C is Container). So we are doing autofac initialization everytime and especially this line :

IContainer C = builder.Build();

Takes a lot of time. My (obvious) solution was to do this once and then create IContainer child and do

child = C ;

and resolve from child. Sadly, they share registrations when I do it this way so I was wondering if there is any way to address this issue without scopes.

Thanks

Peter

There's really not a way to "copy registrations" from one container to another.

You are right - if you can switch things to resolve from a lifetime scope instead of a container, it'd be way better. I don't imagine it'd be that hard to do - as long as the container is accessed by a property or something, it sounds like you have a base class where you could switch the property to return ILifetimeScope rather than IContainer and it shouldn't break things if you're only doing resolutions.

However, if you need to share registrations (for whatever reason) the supported mechanism is to package them into Autofac modules . This would allow you to do something like this:

public class CommonRegistrations : Module
{
  protected override void Load(ContainerBuilder builder)
  {
    // Put your common registrations here.
    builder.RegisterType<Common>().As<ICommon>();
  }
}

When you're setting up your container, rather than copying things, use the module to register the common things.

var builder = new ContainerBuilder();
builder.RegisterModule<CommonRegistrations>();
var container = builder.Build();

Of course, if the build of the container is what's giving you trouble, the module approach won't save you. The only thing that will, really, is switching to use lifetime scopes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM