Register default instance in StructureMap

I have a class ( MyService) that has a static property ( MyService.Context) that represents the current context (which is specific to the current user, so it changes).

What am I trying to achieve i

ObjectFactory.Initialize(x =>
            {
                x.For<IMyService>().Use<MyInstance>(c => c.Use(MyService.Context));
            });

those. so for each ObjectFactory.GetInstance<IMyService>()I get a link toMyService.Context

Is this doable?

UPDATE

I can’t use a singleton template because it MyService.Contextchanges depending on the user making the request (via HttpContext).

In the pseudocode above lambda, the parameter crepresents the SM context, so that I can return a custom result for each request. I know SM Intercept(), but it starts after the object is constructed - instead.

+1
2

, OnCreation. :

ObjectFactory.Initialize(x =>
        {
            x.For<IMyService>()
             .Use<MyInstance>()
             .OnCreation(x => x.Context = MyService.Context;
        });

Func Use, , . :

ObjectFactory.Initialize(x =>
        {
            x.For<IMyService>()
             .Use<MyInstance>(() => new MyInstance(MyService.Context);
        });

, .

+3

, MyService ctor IContext:

For<IContext>().Add(c => MyService.Context).Named("context");
For<IMyService>().Use<MyService>()
    .Ctor<IContext>().Is(c => c.GetInstance<IContext>("context"));

:

For<IContext>().Use(() => MyService.Context);
For<IMyService>().Use<MyService>();

MyService.

0

All Articles