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 ?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With