开发者

Dealing with relationships and potential inconsistencies with DI / IoC

开发者 https://www.devze.com 2023-01-11 22:34 出处:网络
I开发者_如何转开发\'m having trouble designing classes to best make use of DI / IoC principles, particularly when a class shares a dependency with one of its dependencies (ie. X has dependencies Y and

I开发者_如何转开发'm having trouble designing classes to best make use of DI / IoC principles, particularly when a class shares a dependency with one of its dependencies (ie. X has dependencies Y and Z, and Y has dependency Z).

An example will probably be useful:

Lets say I have a class that will encapsulate some connection information for my app. Call it 'ConnectionInfo'

class ConnectionInfo
{
    // ...
}

I've designed a worker class that uses the connection info, so I'll be injecting my dependencies through the constructor.

class Worker 
{
    public Worker(ConnectionInfo c) 
    {
        // ...
    }
}

Now, lets say I want to build another class. It needs access to the connection info, but I also want to have access to the functionality provided by the Worker class.

class AnotherClass
{
    public AnotherClass(ConnectionInfo c, Worker w)
    {
       // ...
    }
}

This is all well and good. However, there is an implied logical relationship between the ConnectionInfo object injected into the Worker, and the ConnectionInfo object injected into the AnotherClass. The design only makes sense when they are one and the same. This isn't enforced, though. There is nothing stopping one ConnectionInfo being injected into AnotherClass, and a completely unrelated ConnectionInfo being injected into Worker.

Am I dealing with IoC / DI in the wrong way?

Should the classes be designed differently, or should the issues be handled in another way (such as enforcing via parameter validation, or maybe just leaving it up to the IoC container)?


i don't think that there is a problem with the Class design

when your client code needs an object of AnotherClass than it will create it's own dependencies of ConnectonInfo and Worker.

There are actually 2 scenarios.

1- Is ur ConnectionInfo and Worker are Singletons : in that case, if you create an object of AnotherClass than same objects of ConnectionInfo and Worker will be shared by the AnotherClass.

2- If point 1 is not true : Than every time you create your AnotehrClass, Container will inject dependencies as a fresh objects.

But for ConnectionInfo , i might say that it may be a Sigleton object becuase it's the common information which needs by your application so i would say that make ConectionInfo as Singleton and rest is fine , i don't think you are violating any IoC rules.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号