How to use Autofac in a class library project?

Brendan Vogt picture Brendan Vogt · Feb 1, 2011 · Viewed 17.8k times · Source

I have the following implementation:

private INewsRepository newsRepository;

public NewsService(INewsRepository newsRepository)
{
     this.newsRepository = newsRepository;
}

This service is in a separate project than that of my web project. Where and how would I specify the dependency injection? Would I still need to put it in my global.asax file? What if this service is used my other apps as well?

Answer

Mark Seemann picture Mark Seemann · Feb 1, 2011

You should only reference the container from the root of the application (global.asax). This is known as the Register Resolve Release pattern.

Your correct use of Constructor Injection ensures that you can reuse the NewsService class from other applications without requiring that those other applications use a particular DI Container (or any at all).

This is a good start at designing the service in a DI Friendly manner, yet keeping it container agnostic.