JasperFx / lamar

Fast Inversion of Control Tool and Successor to StructureMap
https://jasperfx.github.io/lamar
MIT License
566 stars 117 forks source link

Getting ParentType in Lamar #249

Closed marisks closed 3 years ago

marisks commented 4 years ago

Is it possible to get a ParentType when constructing an instance like it was in StructureMap? I see some StructureMap tests in the Lamar repository that does it: https://github.com/JasperFx/lamar/blob/master/src/StructureMap.Testing/Acceptance/contextual_building.cs#L19

Basically, I need to configure the logger same way as in these tests, but can't find a way to get ParentType:

x.For<Logger>().Use(c => LoggerFactory.LoggerFor(c.ParentType)).AlwaysUnique();
jeremydmiller commented 4 years ago

Sigh. I answer this exact question about once a week but always forget to document the solution.

No, but even with StructureMap I was trying to push folks away from that. See the LoggerConvention in this bit of old StructureMap docs: https://structuremap.github.io/the-container/working-with-the-icontext-at-build-time/

See the instance policies in this page for the Lamar mechanics to adapt LoggerConvention: https://jasperfx.github.io/lamar/documentation/ioc/registration/policies/

marisks commented 4 years ago

Thanks @jeremydmiller ! Yeah, an example in docs would help.

marisks commented 4 years ago

This convention worked for me:

public class LoggerConvention : ConfiguredInstancePolicy
{
    protected override void apply(IConfiguredInstance instance)
    {
        instance.ImplementationType
            .GetConstructors()
            .SelectMany(x => x.GetParameters())
            .Where(param => param.ParameterType == typeof(ILog))
            .ForEach(param => instance.Ctor<ILog>()
                                      .Is(LogManager.GetLogger(instance.ImplementationType)));
    }
}