koo9
koo9

Reputation: 409

How to use Autofac container to resolve an instance of a type?

In a windows service, how should one get an instance of a class?

obviously new up an instance will defect the whole purpose of DI. in the old days, one would do

ISomeInterface st = container.Resolve<ISomeInterface>();

in this case, the class that implements ISomeInterface has a dependency class/interface in its contructor e.g. SomeInterfaceImp(IOtherInterface oi)().

how to do this with autofac?

Upvotes: 3

Views: 5849

Answers (1)

Travis Illig
Travis Illig

Reputation: 23894

This is pretty standard dependency resolution/automatic wire-up stuff. As long as you have all of your dependencies in the container, resolving ISomeInterface will automatically also chain in any dependencies like IOtherInterface.

var builder = new ContainerBuilder();
builder.RegisterType<SomeInterfaceImp>().As<ISomeInterface>();
builder.RegisterType<OtherInterfaceImp>().As<IOtherInterface>();
var container = builder.Build();

There is a good getting started guide on Autofac with lots of examples on the Autofac doc site. I suggest you start there.

Note that if you are writing a long-running Windows service (as suggested by your tags) you should not resolve things out of the container because you may end up with a memory leak. There is plenty of documentation about this as well.

Upvotes: 4

Related Questions