Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1087931
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:00:11+00:00 2026-05-16T23:00:11+00:00

As far as I have understood, dependency injection separates the application wiring logic from

  • 0

As far as I have understood, dependency injection separates the application wiring logic from the business logic. Additionally, I try to adhere to the law of Demeter by only injecting direct collaborators.

If I understand this article correctly, proper dependency injection means that collaborators should be fully initialized when they are injected, unless lazy instantiation is required. This would mean (and is actually mentioned in the article) that objects like database connections and file streams should be up and ready at injection time.

However, opening files and connections could result in an exception, which should be handled at some point. What is the best way to go about this?

I could handle the exception at ‘wire time’, like in the following snippet:

class Injector: 
    def inject_MainHelper(self, args): 
        return MainHelper(self.inject_Original(args)) 

    def inject_Original(self, args): 
        return open(args[1], 'rb') 

class MainHelper: 
    def __init__(self, original): 
        self.original = original 

    def run(self): 
        # Do stuff with the stream 

if __name__ == '__main__': 
    injector = Injector() 
    try: 
        helper = injector.inject_MainHelper(sys.argv) 
    except Exception: 
        print "FAILED!" 
    else: 
        helper.run() 

This solution, however, starts to mix business logic with wiring logic.

Another solution is using a provider:

class FileProvider:
    def __init__(self, filename, load_func, mode):
        self._load = load_func
        self._filename = filename
        self._mode = mode

    def get(self):
        return self._load(self._filename, self._mode)

class Injector:
    def inject_MainHelper(self, args):
        return MainHelper(self.inject_Original(args))

    def inject_Original(self, args):
        return FileProvider(args[1], open, 'rb')

class MainHelper:
    def __init__(self, provider):
        self._provider = provider

    def run(self):
        try:
            original = self._provider.get()
        except Exception:
            print "FAILED!"
        finally:
            # Do stuff with the stream

if __name__ == '__main__':
    injector = Injector()
    helper = injector.inject_MainHelper(sys.argv)
    helper.run()

The drawback here is the added complexity of a provider and a violation of the law of Demeter.

What is the best way to deal with exceptions like this when using a dependency-injection framework as discussed in the article?


SOLUTION, based on the discussion with djna

First, as djna correctly points out, there is no actual mixing of business and wiring logic in my first solution. The wiring is happening in its own, separate class, isolated from other logic.

Secondly, there is the case of scopes. Instead of one, there are two smaller scopes:

  • The scope where the file is not verified yet. Here, the injection engine cannot assume anything about the file’s state yet and cannot build objects that depend on it.
  • The scope where the file is successfully opened and verified. Here, the injection engine can create objects based on the extracted contents of the file, without the worry of blowing up on file errors.

After entering the first scope and obtaining enough information on opening and validating a file, the business logic tries to actually validate and open the file (harvesting the fruit, as djna puts it). Here, exceptions can be handled accordingly. When it is certain the file is loaded and parsed correctly, the application can enter the second scope.

Thirdly, not really related to the core problem, but still an issue: the first solution embeds business logic in the main loop, instead of the MainHelper. This makes testing harder.

class FileProvider:
    def __init__(self, filename, load_func):
        self._load = load_func
        self._filename = filename

    def load(self, mode):
        return self._load(self._filename, mode)

class Injector:
    def inject_MainHelper(self, args):
        return MainHelper(self.inject_Original(args))

    def inject_Original(self, args):
        return FileProvider(args[1], open)

    def inject_StreamEditor(self, stream):
        return StreamEditor(stream)

class MainHelper:
    def __init__(self, provider):
        self._provider = provider

    def run(self):
        # In first scope
        try:
            original = self._provider.load('rb')
        except Exception:
            print "FAILED!"
            return
        # Entering second scope
        editor = Injector().inject_StreamEditor(original)
        editor.do_work()


if __name__ == '__main__':
    injector = Injector()
    helper = injector.inject_MainHelper(sys.argv)
    helper.run()

Note that I have cut some corners in the last snippet. Refer to the mentioned article for more information on entering scopes.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T23:00:12+00:00Added an answer on May 16, 2026 at 11:00 pm

    I’ve had discussion about this in the contect of Java EE, EJB 3 and resources.

    My understanding is that we need to distinguish between injection of the Reference to a resource and the actual use of a resource.

    Take the example of a database connection we have some pseudo-code

     InjectedConnectionPool icp;
    
     public void doWork(Stuff someData) throws Exception{
    
           Connection c = icp.getConnection().
           c.writeToDb(someData); 
           c.close(); // return to pool
    
    
     }
    

    As I understand it:

    1). That the injected resource can’t be the connection itself, rather it must be a connection pool. We grab connections for a short duration and return them.
    2). That any Db connection may be invalidated at any time by a failure in the DB or network. So the connection pooling resource must be able to deal with throwing away bad connections and getting new ones.
    3). A failure of injection means that the component will not be started. This could happen if, for example, the injection is actually a JNDI lookup. If there’s no JNDI entry we can’t find the connection pool definition, can’t create the pool and so can’t start the component. This is not the same as actually opening a connection to the DB …
    4). … at the time of initialisation we don’t actually need to open any connections, a failure to do so just gives us an empty pool – ie. exactly the same state as if we had been running for a while and the DB went away, the pool would/could/should throw away the stale connections.

    This model seems to nicely define a set of responsibilities that Demeter might accept. Injection has respobilitiy to prepare the ground, make sure that when the code needs to do something it can. The code has the responsibility to harvest the fruit, try to use the prepared material and cope with actual resource failures and opposed to failures to find out about resources.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

As far as I understand, main purpose of dependency injection is to have all
So far I have only been updated a view from within its controller. I
So far i have an assembly script that lets you boot from it and
I want to understand exactly what unit test means. From what I have understood
I have been reading a lot about dependency injection recently, and in theory it
As far as I have understood so far, every time I draw something in
As far as I have understood, querySelector returns a real changeable element while querySelectorAll
I have a question concerning dependency injection. I have been keeping it simple so
I have just begun my journey in Maven2 and found the dependency repositories logic
I'm reading The C Programming Language and have understood everything so far. However when

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.