Search code examples
c#autofac

Resolve class and register return object from one method


I have a class Factory which has a constructor that takes one parameter and a Create method that returns IClient object.

class Factory
{
  public Factory(SomeParam someParam) 
  { /*...*/ }

  public IClient Create()
  { /*...*/ }
}

How can I register that Factory in autofac ?


Solution

  • You should first register your factory and then register a delegate which will resolve the factory and return the `IClient.

    Of course SomeParam should also be registered in Autofac

    builder.RegisterType<ClientFactory>()
           .As<IClientFactory>();
    builder.Register(ctx => ctx.Resolve<IClientFactory>().Create())
           .As<IClient>();