The requested service has not been registered ! AutoFac Dependency Injection
32,866
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();
Author by
Barış Velioğlu
Updated on April 04, 2020Comments
-
Barış Velioğlu about 4 years
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 ?