Create instances of a class that requires a constructor argument with StructureMap

I have the following classes:

public class AllowanceManager : IAllowanceManager
{
    public AllowanceManager(ITranslationManager t_Manager, ISessionManager s_Manager)
    {...}
}

public class TranslationManager : ITranslationManager
{
    public TranslationManager(string culture) 
    {...}
}

public class SessionManager : ISessionManager
{
    public SessionManager(string key) 
    {...}
}

How to initialize these classes in ObjectFactory to get an instance of IAllowanceManager is also autwires and initializes (with constructor arguments) StateManager and TranslationManager. So I only need to restore the IAllowanceDeduction instance as follows:

IAllowanceManager a_Manager = ObjectFactory....// Gets Allowancemanager configured    with initialized instances of IStateManager and ITranslationManager
+3
source share
3 answers

Edit: even shorter.

Put this in your bootstrap code:

ForRequestedType<IAllowanceManager>().TheDefault.Is
       .ConstructedBy(() => new Allowancemanager(new StateManager(), new TranslationManager()));
+1
source

Using syntax 2.6.1, it can be written:

For<ISessionManager>().Use<SessionManager>()
  .Ctor<string>("key").Is(c => GetSessionKey());
For<ITranslationManager>().Use<TranslationManager>()
  .Ctor<string>("culture").Is(c => Thread.CurrentThread.CurrentCulture.Name);
For<IAllowanceManager>.Use<AllowanceManager>();

where GetSessionKey returns your session key in the manner that culture permits.

, .

+1

:

IStateManager stateManager = ObjectFactory
    .With<string>("key")
    .GetInstance<IStateManager>();

ITranslationManager translationManager = ObjectFactory
    .With<string>("culture")
    .GetInstance<ITranslationManager>();

manager = ObjectFactory
    .With<ITranslationManager>(translationManager)
    .With<IStateManager>(stateManager)
    .GetInstance<IAllowanceDeductionManager>();
0
source

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


All Articles