Using the Lamar DI container, how do you build objects with a lambda given a type?

402 Views Asked by At

Lamar provides the following syntax for building objects with a lambda:

serviceRegistry.For<ISomeType>().Use(x => { ... });

This would allow you to resolve ISomeType which would execute the registered delegate:

 var someType = container.GetInstance<ISomeType>();

Is there a non-generic equivalent such as the following?

serviceRegistry.For(typeof(ISomeType)).Use(x => { ... });

I'm not seeing an overload for this.

1

There are 1 best solutions below

0
Derek Greer On

After discovering that Lamar's ServiceRegistry is derived from ServiceProvider, I realized that it would be possible to achieve this by using the ServiceProvider API:

var container = new Container(x => x.Add(new ServiceDescriptor(typeof(string), sp => "test", ServiceLifetime.Singleton)));
Console.WriteLine(container.GetService<string>());

See .Net Fiddle Example