Home > other >  Register lambda as factory (with dependencies)
Register lambda as factory (with dependencies)

Time:03-11

I'm trying to migrate from Grace IOC container to Autofac.

In Grace, I could do this kind of registration (original source):

block.ExportFactory<SimpleObjectA, SimpleObjectB, SimpleObjectC, IEnumerable<ISimpleObject>>(
                    (a, b, c) => new List<ISimpleObject> { a, b, c });`

In summary, it takes a lambda expression as factory, whose arguments are resolved and supplied by the container to it.

In Autofac, all I have found is:

containerBuilder.Register((context, parameters) => new Service(...));

CodePudding user response:

In Autofac it's up to you to resolve the dependencies in the lambda. The registration you found is correct.

Let's say your lambda is a => new Service(a) and that's the factory. I say that because the Grace example you showed would automatically be handled by Autofac supporting IList<T>.

You'd register that like:

builder.Register(ctx =>
  {
    var a = ctx.Resolve<IDependency>();
    return new Service(a);
  });

If you want to use parameters, you can.

builder.Register((ctx, p) =>
  {
    var a = p.Typed<IDependency>();
    return new Service(a);
  });

However, there are even more things you can do which may also help, and for which I won't duplicate the documentation. It could be that you don't need to register a lambda at all, that Autofac will do some of this for you. You'll want to check out...

There are a lot of options here, it all depends on what you're trying to achieve... which isn't honestly 100% clear from the question. Hopefully this will get you going in the right direction.

  • Related