Type StructureMap requested

Is it possible to pass the requesting type as a parameter when setting up the StructureMap container.

For instance:

            container.Configure(x => {
                x.For<ILogger>().Use(new TestLogger(log.Add, requestingType));         
            });

Where the requesting type is the type of consumption object:

public class SomeClass
{
    private readonly ILogger logger;
    public SomeClass(ILogger logger)
    {
        this.logger = logger;
    }
}

Thus, the type passed to the log will be SomeNamespace.SomeClass.

Thanks Ben

+3
source share
3 answers

You can easily access the requested type using ICMontext StructureMap.

ObjectFactory.Configure(
    x => {
        x.For<ILogger>().Use( context => new TestLogger( context.ParentType ) );
    } );

In the above description, context.ParentType returns the type that StructureMap creates.

Jeremy Miller also covered this topic on his blog. This article uses outdated syntax, but it still matters: http://codebetter.com/jeremymiller/2009/01/15/using-the-build-session-in-structuremap/

IContext, :

ObjectFactory.Configure(
    x => {
        x.For<ILogger>()
                .Use( context =>
                {
                    // Set breakpoint here and inspect the context
                    return new TestLogger( context.ParentType );
                } );
    } );

Update:

.AlwaysUnique() ( .CacheBy(InstanceScope.Unique)), StructureMap ILogger, , ILogger GetInstance().

, , ILogger, ObjectFactory.GetInstance <ISomeClass> () ILogger , ILogger, , , .

, , :

x.For<ILogger>()
    .AlwaysUnique()
    .Use( c => new TestLogger( c.ParentType ?? c.BuildStack.Current.ConcreteType ) );
+3

ILogger ILogger<T> StructureMap.

, , , , , , - .

0

First, I want to specify potential information by registering an instance with Use (new Type ()) so that this instance is registered as a single. To avoid this, you can use Use (() => new Type ()).

Here's how you get the requested type during setup:

container.Configure(x => {
  x.For<ILogger>().Use(c => new TestLogger(log.Add, c.Root.RequestedType));
});
0
source

Source: https://habr.com/ru/post/1769780/


All Articles