Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Autofac how do I change the instance that is registered after Build has been called?

So lets say i have this code

var builder = new ContainerBuilder(); builder.RegisterInstance(new MyType()); var container = builder.Build(); 

Then some time later I want to change the instance of MyType for all future resolves that are called on container.

like image 575
Simon Avatar asked Oct 18 '10 03:10

Simon


People also ask

How do I register an Autofac interface?

Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.

How do I register a generic repository in Autofac?

You need to exactly write like this: builder. RegisterGeneric(typeof(RepositoryBase<>)) . As(typeof(IRepository<>)); note the empty <> and it will register your Repository for all of your entites.

Is Autofac a framework?

Autofac has the reputation of being the most widely used framework in the . NET community. It is one of the most downloaded packages among developers. AutoFac provides better integration for the ASP.NET MVC framework and is developed using Google code.


1 Answers

At the time you want to change the registration, create a new ContainerBuilder, register the new instance, and call Update passing in the container:

// at some later point... builder = new ContainerBuilder(); builder.RegisterInstance(myType2); builder.Update(container); 
like image 51
Jeff Ogata Avatar answered Sep 21 '22 06:09

Jeff Ogata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!