Designer options for dependent classes with Unity Framework

I just started using the Unity application block to separate my classes and simplify unit testing. However, I had a problem with circular dependencies.

I have a facade type class that is a chat bot. This is a singleton class that handles all kinds of secondary classes and provides a central place to launch and configure the bot. I also have a class called AccessManager that, well, controls access to bot commands and resources. Restraining myself to the point, I have classes configured like this:

public class Bot
{
    public string Owner { get; private set; }
    public string WorkingDirectory { get; private set; }

    private IAccessManager AccessManager;

    private Bot()
    {
       // do some setup

       // LoadConfig sets the Owner & WorkingDirectory variables
       LoadConfig();

       // init the access mmanager
       AccessManager = new MyAccessManager(this);
    }

    public static Bot Instance()
    {
       // singleton code
    }

    ...
}

And the AccessManager class:

public class MyAccessManager : IAccessManager
{
    private Bot botReference;

    public MyAccesManager(Bot botReference)
    {
        this.botReference = botReference;
        SetOwnerAccess(botReference.Owner);
    }

    private void LoadConfig()
    {
        string configPath = Path.Combine(
            botReference.WorkingDirectory, 
            "access.config");
        // do stuff to read from config file
    }

    ...
}

, Unity Application Block. Unity Singleton One Bot AccessManager - , , - .

public static void BootStrapSystem()
{
   IUnityContainer container = new UnityContainer();

   // create new bot instance
   Bot newBot = Bot.Instance();

   // register bot instance 
   container.RegisterInstance<Bot>(newBot);

   // register access manager
   container.RegisterType<IAccessManager,MyAccessManager>(newBot);
}

Access Manager Bot, :

IAcessManager accessManager = container.Resolve<IAccessManager>();

, Bottonton:

// do this
Bot botInstance = container.Resolve<Bot>();
// instead of this
Bot botInstance = Bot.Instance();

, BootStrapSystem() . , IAccessManager, , ( ). Bot, Bot ! !! !!!

, , . ? !!

+3
2

, :

  • Singleton . DI , Bot. , Unity, .
  • , . , , . - Mediator.

, Unity. Unity ( DI) , . DI, DI , .

+1

, singleton, . , . initialize.

container.RegisterType<Bot>(new ContainerControlledLifecycleManager()); // from my memory...
container.RegisterType<IAccessManager,MyAccessManager>();

var bot = container.Resolve<Bot>();

// Bot.cs
public Bot(IAccessManager manager)
{
   manager.InitializeFor(this);
}

IOC .

+1

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


All Articles