Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The requested service has not been registered ! AutoFac Dependency Injection

I am simply trying to use AutoFac to resolve dependencies but it throws exception such as

The requested service 'ProductService' has not been registered. To avoid this exception, either register a component to provide service or use IsRegistered()...

class Program {     static void Main(string[] args)     {         var builder = new ContainerBuilder();          builder.RegisterType<ProductService>().As<IProductService>();          using (var container = builder.Build())         {             container.Resolve<ProductService>().DoSomething();         }     } }  public class ProductService : IProductService {     public void DoSomething()     {         Console.WriteLine("I do lots of things!!!");     } }  public interface IProductService {     void DoSomething(); } 

What I have done wrong ?

like image 250
Barış Velioğlu Avatar asked Mar 16 '13 12:03

Barış Velioğlu


1 Answers

With the statement:

builder.RegisterType<ProductService>().As<IProductService>(); 

Told Autofac whenever somebody tries to resolve an IProductService give them an ProductService

So you need to resolve the IProductService and to the ProductService:

using (var container = builder.Build()) {     container.Resolve<IProductService>().DoSomething(); } 

Or if you want to keep the Resolve<ProductService> register it with AsSelf:

builder.RegisterType<ProductService>().AsSelf(); 
like image 152
nemesv Avatar answered Oct 04 '22 12:10

nemesv