Creating New Instances Using Injection Dependency

Brief description of the environment:

I have a class that is a chat and has a registrar dependency. This is not the same as a system logger with multiple problems, but the logger associated with this particular chat. It logs all activity in this chat for a unique log file. When a chat is created, I want to open the log file, and when it is destroyed, I want to close the log file.

Problem

Here is the relevant code that I use.

public interface IChatroomLogger
{
    void Log(ServerPacket packet);
    void Open();
    void Close();
}

public class ChatroomLogger : IChatroomLogger
{
    // chatroom name will be used as a file name
    public ChatroomLogger(string chatroomName) { ... }
    public void Log(ServerPacket packet) { ... }
}

public class Chatroom
{
    public Chatroom(string name, IChatroomLogger logger)
    {
        this.name = name;
        this.logger = logger;
        this.logger.Open();
    }

    public IChatromLogger Logger { get { return this.logger; } }
}

public interface IChatManager
{
    Chatroom Get(chatroomName);
}

It is used in the application as follows:

var room = ChatManager.Get(chatroomName);
romm.DoStuff();
room.Logger.LogPacket(receivedPacket);

ChatManager- This is a class that contains links to all chats and is responsible for their creation and deletion. I haven't written this yet, but the interface I encoded.

Question

ChatManager Chatroom - ?

Unity, . . , .

ChatManager , IChatroomLogger. , ... Unity . IUnityContainer ChatManager.

public class ChatManager : IChatManager
{
    public ChatManager(IUnityContainer container)
    {
        this.container = container;
    }

    public Chat Get(string chatroomName)
    {
        // get logger from Unity somehow. Not sure how I'd 
        // pass chatroomName to the concrete instance
        var logger = ...
        return new Chatroom(chatroomName, logger);
    }
}

- - . , , DI.

Chatroom, , - ? ? ? !

+5
2

. IUnityContainer Injection Dependency. "Locator". , , IFactory<T>, :

public IFactory<T>
{
    T Get();
}

, IUnityContainer. , IFactory<> factory. , IFactory<Logger> ChatManager .Get() , .

+4

, , .

  • ICchatroomProvider Create (stringnamename)
  • ChatroomProvider ( , ).
  • ChatroomProvider
  • ChatManager IChatroomProvider
  • ChatManager , IChatroomProvider
  • ChatManager
  • .
+1

All Articles