EzDevInfo.com

dependency-injection interview questions

Top dependency-injection frequently asked interview questions

AngularJS: Service vs provider vs factory

What are the differences between AngularJS module's Service, Provider and Factory?


Source: (StackOverflow)

What is dependency injection?

There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,

What is dependency injection and when/why should or shouldn't it be used?


Source: (StackOverflow)

Advertisements

What are the downsides to using Dependency Injection? [closed]

I'm trying to introduce DI as a pattern here at work and one of our lead developers would like to know: What - if any - are the downsides to using the Dependency Injection pattern?

Note I'm looking here for an - if possible - exhaustive list, not a subjective discussion on the topic.


Clarification: I'm talking about the Dependency Injection pattern (see this article by Martin Fowler), not a specific framework, whether XML-based (such as Spring) or code-based (such as Guice), or "self-rolled".


Edit: Some great further discussion / ranting / debate going on /r/programming here.


Source: (StackOverflow)

Dependency Injection vs Factory Pattern

Most of the examples quoted for usage of Dependency Injection, we can solve using the factory pattern as well. Looks like when it comes to usage/design the difference between dependency injection and factory is blurred or thin.

Once someone told me that its how you use it that makes a difference!

I once used StructureMap a DI container to solve a problem, later on I redesigned it to work with a simple factory and removed references to StructureMap.

Can anyone tell me what is the difference between them and where to use what, whats the best practice here?


Source: (StackOverflow)

Which .NET Dependency Injection frameworks are worth looking into? [closed]

Which C#/.NET Dependency Injection frameworks are worth looking into? And what can you say about their complexity and speed.


Source: (StackOverflow)

One DbContext per web request... why?

I have been reading a lot of articles explaining how to set up Entity Framework's DbContext so that only one is created and used per HTTP web request using various DI frameworks.

Why is this a good idea in the first place? What advantages do you gain by using this approach? Are there certain situations where this would be a good idea? Are there things that you can do using this technique that you can't do when instantiating DbContexts per repository method call?


Source: (StackOverflow)

How to explain dependency injection to a 5-year-old? [closed]

What is a good dependency injection tutorial?

I found a ton on Google, but none of them that would assume the reader is just a Java beginner.


Source: (StackOverflow)

@Resource vs @Autowired

Which annotation, @Resource (jsr250) or @Autowired (Spring specific) should I be using when using DI?

I have successfully used both in the past, @Resource(name="blah") and @Autowired @Qualifier("blah")

My instinct is to stick with the @Resource tag since it's been ratified by the jsr people. Anyone have strong thoughts on this?


Source: (StackOverflow)

How do the major C# DI/IoC frameworks compare?

At the risk of stepping into holy war territory, What are the strengths and weaknesses of these popular DI/IoC frameworks, and could one easily be considered the best? ..:

  • Ninject
  • Unity
  • Castle.Windsor
  • Autofac
  • StructureMap

Are there any other DI/IoC Frameworks for C# that I haven't listed here?

In context of my use case, I'm building a client WPF app, and a WCF/SQL services infrastructure, ease of use (especially in terms of clear and concise syntax), consistent documentation, good community support and performance are all important factors in my choice.

Update:

The resources and duplicate questions cited appear to be out of date, can someone with knowledge of all these frameworks come forward and provide some real insight?

I realise that most opinion on this subject is likely to be biased, but I am hoping that someone has taken the time to study all these frameworks and have at least a generally objective comparison.

I am quite willing to make my own investigations if this hasn't been done before, but I assumed this was something at least a few people had done already.

Second Update:

If you do have experience with more than one DI/IoC container, please rank and summarise the pros and cons of those, thank you. This isn't an exercise in discovering all the obscure little containers that people have made, I'm looking for comparisons between the popular (and active) frameworks.


Source: (StackOverflow)

Why does one use dependency injection? [closed]

I'm trying to understand dependency injections (DI), and once again I failed. It just seems silly. My code is never a mess; I hardly write virtual functions and interfaces (although I do once in a blue moon) and all my configuration is magically serialized into a class using json.net (sometimes using an XML serializer).

I don't quite understand what problem it solves. It looks like a way to say: "hi. When you run into this function, return an object that is of this type and uses these parameters/data."
But... why would I ever use that? Note I have never needed to use object as well, but I understand what that is for.

What are some real situations in either building a website or desktop application where one would use DI? I can come up with cases easily for why someone may want to use interfaces/virtual functions in a game, but it's extremely rare (rare enough that I can't remember a single instance) to use that in non-game code.


Source: (StackOverflow)

How can I inject a property value into a Spring Bean which was configured using annotations?

I have a bunch of Spring beans which are picked up from the classpath via annotations, e.g.

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
    // Implementation omitted
}

In the Spring XML file, there's a PropertyPlaceholderConfigurer defined:

<bean id="propertyConfigurer" 
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/app.properties" />
</bean> 

I want to inject one of the properties from app.properites into the bean shown above. I can't simply do something like

<bean class="com.example.PersonDaoImpl">
    <property name="maxResults" value="${results.max}"/>
</bean>

Because PersonDaoImpl does not feature in the Spring XML file (it is picked up from the classpath via annotations). I've got as far as the following:

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

    @Resource(name = "propertyConfigurer")
    protected void setProperties(PropertyPlaceholderConfigurer ppc) {
    // Now how do I access results.max? 
    }
}

But it's not clear to me how I access the property I'm interested in from ppc?


Source: (StackOverflow)

Dependency Inject (DI) "friendly" library

I'm pondering the design of a C# library, that will have several different high level functions. Of course, those high-level functions will be implemented using the SOLID class design principles as much as possible. As such, there will probably be classes intended for consumers to use directly on a regular basis, and "support classes" that are dependencies of those more common "end user" classes.

The question is, what is the best way to design the library so it is:

  • DI Agnostic - Although adding basic "support" for one or two of the common DI libraries (StructureMap, Ninject, etc) seems reasonable, I want consumers to be able to use the library with any DI framework.
  • Non-DI usable - If a consumer of the library is using no DI, the library should still be as easy to use as possible, reducing the amount of work a user has to do to create all these "unimportant" dependencies just to get to the "real" classes they want to use.

My current thinking is to provide a few "DI registration modules" for the common DI libraries (e.g a StructureMap registry, a Ninject module), and a set or Factory classes that are non-DI and contain the coupling to those few factories.

Thoughts?


Source: (StackOverflow)

Inversion of Control vs Dependency Injection

According to the paper written by Martin Fowler: http://martinfowler.com/bliki/InversionOfControl.html , inversion of control is the principle where the control flow of a program is inverted: instead of the programmer controlling the flow of a program, the external sources (framework, services, other components) take control of it. It's like we plug something into something else. He mentioned an example about EJB 2.0:

For example the Session Bean interface defines ejbRemove, ejbPassivate (stored to secondary storage), and ejbActivate (restored from passive state). You don't get to control when these methods are called, just what they do. The container calls us, we don't call it.

This leads to the difference between framework and library:

Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.

I think, the point of view that DI is IOC, means the dependency of an object is inverted: instead it controls its own dependencies, life cycle... something else does it for you. But, as you told me about DI by hands, DI is not necessary IOC. We can still have DI and no IOC.

However, in this paper (from the pococapsule, another IOC Framework for C/C++), it suggests that because of IOC and DI, the IOC containers and DI frameworks are far more superior to J2EE, since J2EE mixes the framework code into the components, thus not making it Plain Old Java/C++ Object (POJO/POCO).

Inversion of Control Containers other than the Dependency Injection pattern: http://www.pocomatic.com/docs/whitepapers/ioc-vs-di/

Additional reading to understand what's the problem with old Component-Based Development Framework, which leads to the second paper above: Why and what of Inversion of Control: http://www.pocomatic.com/docs/whitepapers/ioc/

My Question: What's exactly is IOC and DI? I am confused. Based on pococapsule, IOC is something more significant than just invert the control of objects or between programmers and frameworks.


Source: (StackOverflow)

Injecting Mockito mocks into a Spring bean

I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired annotation on private member fields.

I have considered using ReflectionTestUtils.setField but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing.

I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.package.Dao" />
</bean>

The error I currently encounter is as follows:

...
Caused by: org...NoSuchBeanDefinitionException:
    No matching bean of type [com.package.Dao] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {
        @org...Autowired(required=true),
        @org...Qualifier(value=dao)
    }
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)

If I set the constructor-arg value to something invalid no error occurs when starting the application context.


Source: (StackOverflow)

How to avoid Dependency Injection constructor madness?

I find that my constructors are starting to look like this:

public MyClass(Container con, SomeClass1 obj1, SomeClass2, obj2.... )

with ever increasing parameter list. Since "Container" is my dependency injection container, why can't I just do this:

public MyClass(Container con)

for every class? What are the downsides? If I do this, it feels like I'm using a glorified static. Please share your thoughts on IoC and Dependency Injection madness.


Source: (StackOverflow)