Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac delegate factory using func<>

I am trying to understand the delegate factory pattern with Autofac. I know how to implement factory using IIndex<> with Keyed() registration, which is explained nicely in here: Configuring an Autofac delegate factory that's defined on an abstract class

I would like to know if I can create a factory using Func<>, and how would I do the registrations for the following sample:

public enum Service
{
   Foo,
   Bar
}

public interface FooService : IService 
{
   ServiceMethod();
}

public interface BarService : IService 
{
   ServiceMethod();
}

public class FooBarClient
{
   private readonly IService service;

   public FooBarClient(Func<Service, IService> service)
   {
      this.service = service(Service.Foo);
   }

   public void Process()
   {
      service.ServiceMethod(); // call the foo service.
   }
}
like image 607
Narayan Akhade Avatar asked Mar 14 '13 22:03

Narayan Akhade


People also ask

How do you call a factory in Autofac?

The factory is a standard delegate that can be called with Invoke () or with the function syntax as shown above.. By default, Autofac matches the parameters of the delegate to the parameters of the constructor by name. If you use the generic Func relationships, Autofac will switch to matching parameters by type.

How does Autofac match the parameters of a delegate to a constructor?

By default, Autofac matches the parameters of the delegate to the parameters of the constructor by name. If you use the generic Func relationships, Autofac will switch to matching parameters by type.

How do you call a factory from a delegate?

The factory is a standard delegate that can be called with Invoke () or with the function syntax as shown above.. By default, Autofac matches the parameters of the delegate to the parameters of the constructor by name.

How to call shareholdingfactory from Autofac?

The factory is a standard delegate that can be called with Invoke (), as above, or with the function syntax shareholdingFactory ("ABC", 1234). By default, Autofac matches the parameters of the delegate to the parameters of the constructor by name.


1 Answers

Autofac cannot construct this Func<Service, IService> for you which lets you return different types based on a parameter. This is what IIndex<> is for.

However if you don't want/cannot use IIndex<> you can create this factory function with the help of the Keyed or Named and register your factory in the container:

var builder = new ContainerBuilder();
builder.RegisterType<FooBarClient>().AsSelf();
builder.RegisterType<FooService>().Keyed<IService>(Service.Foo);
builder.RegisterType<BarService>().Keyed<IService>(Service.Bar);

builder.Register<Func<Service, IService>>(c => 
{
    var context = c.Resolve<IComponentContext>();
    return s => context.ResolveKeyed<IService>(s);
});
like image 120
nemesv Avatar answered Oct 12 '22 23:10

nemesv