Automatically assign constructor parameters to member variables with Autofac? - dependency-injection

When using Autofac I find myself writing a lot of boilerplate code like this:
public class MyClass {
[...]
public MyClass(IFoo foo, IBar bar, IBaz baz) {
_foo = foo;
_bar = bar;
_baz = baz;
}
}
Is there a way of automatically assigning constructor-injected dependencies to their equivalent member variables based on name convention (a la AutoMapper) with Autofac? Or maybe you could use attributes to tell Autofac which properties it should inject, eg.:
[DependencyInjected]
private IFoo _foo;
[DependencyInjected]
private IBar _bar;
[DependencyInjected]
private IBaz _baz;

Is there a way of automatically assigning constructor-injected dependencies to their equivalent member variables based on name convention (a la AutoMapper) with Autofac?
No, not unless you build it yourself. Autofac is only compatible with standard OOP practices, which do not include using Reflection to populate private member variables.
When implementing the Dependency Injection pattern in C# there are 3 different ways that dependencies can be injected:
Constructor Injection
Property Injection (also called Setter injection)
Method Injection
There is no accepted pattern for injecting private member variables. In fact, this cannot be done with standard OO principles, in .NET it can only be accomplished using Reflection.
Also, when using the the Dependency Injection pattern, there is no rule that says you must use a DI container such as Autofac. In fact, the use of a DI container is completely optional when applying the DI pattern. For example, when making unit tests it is easy to use the pattern without Autofac - here is an example that uses NUnit and Moq.
[Test]
public void TestDoSomething()
{
// Arrange
var foo = new Mock<IFoo>();
var bar = new Mock<IBar>();
var baz = new Mock<IBaz>();
var target = new MyClass(foo.Object, bar.Object, baz.Object);
// Act
var result = target.DoSomething();
// Assert
Assert.IsNotNull(result);
// Test other conditions
}
On the other hand, if you add this extra bit of Reflection, you would need access to it in order to populate your MyClass with dependencies.
[Test]
public void TestDoSomething()
{
// Arrange
var foo = new Mock<IFoo>();
var bar = new Mock<IBar>();
var baz = new Mock<IBaz>();
var target = new MyClass();
// Use Reflection to insert the dependencies into the object
InjectDependencies(target, foo.Object, bar.Object, baz.Object);
// Act
var result = target.DoSomething();
// Assert
Assert.IsNotNull(result);
// Test other conditions
}
A big concern here is that the code will compile fine if you completely remove the InjectDependencies(target, foo, bar, baz); line and you will probably end up with a NullReferenceException at runtime somewhere in your class. The purpose of an instance constructor is:
to create and initialize any instance member variables when you use the new expression to create an object of a class.
This guarantees the object is correctly constructed with all of its dependencies. A typical example of the DI pattern with constructor injection:
public class MyClass
{
private readonly IFoo _foo;
private readonly IBar _bar;
private readonly IBaz _baz;
public MyClass(IFoo foo, IBar bar, IBaz baz) {
_foo = foo ?? throw new ArgumentNullException(nameof(foo));
_bar = bar ?? throw new ArgumentNullException(nameof(bar));
_baz = baz ?? throw new ArgumentNullException(nameof(baz));
}
}
The above example uses the readonly keyword and guard clauses in the constructor (which are missing from your example) to guarantee the instance of MyClass cannot be created unless all of its dependencies are supplied. In other words, there is a 0% chance that any of the member variables will ever be null, so you will not have to worry about increasing the complexity of the code by adding null checks to the rest of the class. There is also a 0% chance that any code outside of the constructor can change any of the dependencies, which could cause hard-to-find stability issues with the application.
The bottom line is, you could use Reflection to populate your classes this way if you would like to build your own Autofac extension and write null checks throughout your class, but I wouldn't recommend it because you are taking something that is achieving loose coupling with pure OOP and turning it into a tightly-coupled piece of Reflection code that all of your classes (and anyone who uses them) will depend upon.
You are also removing the possibility of using the handy features of C# that guarantee that the instance will always have all of its dependencies regardless of the context in which it is used (DI container or no DI container) and that they cannot be unwittingly replaced or set to null during runtime.
Workaround
If your primary concern about "boilerplate code" is that you have to type the constructor code yourself, here are a couple of Visual Studio extensions that automate that part:
DependencyInjectionToolset
DiConstructorGeneratorExtension
Unfortunately, neither one of them seems to add the guard clause to the constructor.

Related

Guice multiple implementations, parameterized constructor with dependencies

I'm struggling with a particular dependency injection problem and I just can't seem to figure it out. FYI: I'm new to guice, but I have experience with other DI frameworks - that's why I believe this shouldn't be to complicated to achieve.
What am I doing:
I'm working on Lagom multi module project and using Guice as DI.
What I would like to achieve:
Inject multiple named instances of some interface implementation (lets' call it publisher, since it will publishing messages to kafka topic) to my service.
This 'publisher' has injected some Lagom and Akka related services (ServiceLocator, ActorSystem, Materializer, etc..).
Now I would like to have two instances of such publisher and each will publish messages to different topic (So one publisher instance per topic).
How would I achieve that?
I have no problem with one instance or multiple instances for the same topic, but if I want to inject different topic name for each instance I have a problem.
So my publisher implementation constructor looks like that:
#Inject
public PublisherImpl(
#Named("topicName") String topic,
ServiceLocator serviceLocator,
ActorSystem actorSystem,
Materializer materializer,
ApplicationLifecycle applicationLifecycle) {
...
}
If I want to create one instance I would do it like this in my ServiceModule:
public class FeedListenerServiceModule extends AbstractModule implements ServiceGuiceSupport {
#Override
protected void configure() {
bindService(MyService.class, MyServiceImpl.class);
bindConstant().annotatedWith(Names.named("topicName")).to("topicOne");
bind(Publisher.class).annotatedWith(Names.named("publisherOne")).to(PublisherImpl.class);
}
}
How would I bind multiple publishers each for it's own topic?
I was playing around with implementing another private module:
public class PublisherModule extends PrivateModule {
private String publisherName;
private String topicName;
public PublisherModule(String publisherName, String topicName) {
this.publisherName = publisherName;
this.topicName = topicName;
}
#Override
protected void configure() {
bindConstant().annotatedWith(Names.named("topicName")).to(topicName);
bind(Publisher.class).annotatedWith(Names.named(publisherName)).to(PublisherImpl.class);
}
}
but this led me nowhere since you can't get injector in you module configuration method:
Injector injector = Guice.createInjector(this); // This will throw IllegalStateException : Re-entry is not allowed
injector.createChildInjector(
new PublisherModule("publisherOne", "topicOne"),
new PublisherModule("publisherTwo", "topicTwo"));
The only solution which is easy and it works is that I change my PublisherImpl to abstract, add him abstract 'getTopic()' method and add two more implementations with topic override.
But this solution is lame. Adding additional inheritance for code reuse is not exactly the best practice. Also I believe that Guice for sure must support such feature.
Any advises are welcome.
KR, Nejc
Don't create a new Injector within a configure method. Instead, install the new modules you create. No child injectors needed—as in the PrivateModule documentation, "Private modules are implemented using parent injectors", so there's a child injector involved anyway.
install(new PublisherModule("publisherOne", "topicOne"));
install(new PublisherModule("publisherTwo", "topicTwo"));
Your technique of using PrivateModule is the one I'd go with in this situation, particularly given the desire to make the bindings available through binding annotations as you have it, and particularly if the full set of topics is known at runtime. You could even put the call to install in a loop.
However, if you need an arbitrary number of implementations, you may want to create an injectable factory or provider to which you can pass a String set at runtime.
public class PublisherProvider {
// You can inject Provider<T> for all T bindings in Guice, automatically, which
// lets you configure in your Module whether or not instances are shared.
#Inject private final Provider<ServiceLocator> serviceLocatorProvider;
// ...
private final Map<String, Publisher> publisherMap = new HashMap<>();
public Publisher publisherFor(String topicName) {
if (publisherMap.containsKey(topicName)) {
return publisherMap.get(topicName);
} else {
PublisherImpl publisherImpl = new PublisherImpl(
topicName, serviceLocatorProvider.get(), actorSystemProvider.get(),
materializerProvider.get(), applicationLifecycleProvider.get());
publisherMap.put(topicName, publisherImpl);
return publisherImpl;
}
}
}
You'd probably want to make the above thread-safe; in addition, you can avoid the explicit constructor call by using assisted injection (FactoryModuleBuilder) or AutoFactory, which will automatically pass through explicit parameters like topicName while injecting DI providers like ServiceLocator (which hopefully has a specific purpose, because you may not need much service-locating within a DI framework anyway!).
(Side note: Don't forget to expose your annotated binding for your PrivateModule. If you don't find yourself injecting your topicName anywhere else, you might also consider using individual #Provides methods with the assisted injection or AutoFactory approach above, but if you expect each Publisher to need a differing object graph you might choose the PrivateModule approach anyway.)
Guice's approach to dependency injection is that the DI framework complements your instantiation logic, it doesn't replace it. Where it can, it will instantiate things for you, but it doesn't try to be too clever about it. It also doesn't confuse configuration (topic names) with dependency injection - it does one thing, DI, and does that one thing well. So you can't use it to configure things, the way you can with Spring for example.
So if you want to instantiate an object with two different parameters, then you instantiate that object with two different parameters - ie, you invoke new twice. This can be done by using provider methods, which are documented here:
https://github.com/google/guice/wiki/ProvidesMethods
In your case, it might look something like adding the following method to your module:
#Provides
#Named("publisherOne")
#Singleton
Publisher providePublisherOne(ServiceLocator serviceLocator,
ActorSystem actorSystem,
Materializer materializer,
ApplicationLifecycle applicationLifecycle) {
return new PublisherImpl("topicOne", serviceLocator,
actorSystem, materializer, applicationLifecycle);
}
Also, you probably want it to be a singleton if you're adding a lifecycle hook, otherwise you could run into memory leaks each time you add a new hook every time it's instantiated.

fakeiteasy initializing private members in constructor

I want to test methods in my controller, I know about this...
myController = new MyController();
A.CallTo(()=>myController.SomeMethodIWantToTest().Returns(someValueIAmTesting);
The problem is that inside that parameterless constructor, I call numerous methods in other assemblies that set values for private members,
public class MyController : Controller {
private ILoginBusiness loginBusiness;
private ISomethingElse somethingElse;
//... and so on...
public MyController(){
loginbusiness = ServiceFactory.GetLoginBusiness();
somethingElse = //some method in another assembly that initializes the value
//... and so on, calling methods in other assemblies that initialize the private members...
}
public ActionResult SomeMethodIWantToTest(){ }
}
So how do I isolate all those method calls in my constructor (so I'm not calling methods in those other assemblies?)
First,
myController = new MyController();
A.CallTo(()=>myController.SomeMethodIWantToTest().Returns(someValueIAmTesting);
Will result in an error, as A.CallTo only handles calls to fakes (and there should be an extra ) after …ToTest()).
Second, the general approach that is taken in this sort of situation is called Dependency Injection. Instead of having a class make all its dependencies (in your case, by calling methods from other assemblies), you have its dependencies provided to it.
Assuming you're able to start injecting dependencies, you're almost home. You're already relying on interfaces inside MyController, so then you can use FakeItEasy to supply fakes to MyController, avoiding calls to the out-of-assembly methods.

How to instantiate the repository that uses ninject in a unit test

I have a repository like:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
{
private readonly IContext _db;
public Repository(IContext context)
{
_db =context;
}
...
In Global.asax I have setup the ninject as:
kernel.Bind<IContext>().To<Context>();
This is working fine in the app probably because I'm explicity instantiating by calling the constructor with a paramater. There are problems in the unit tests however.
Then in a unit test I have:
var mockUnitOfWork = new Mock<UnitOfWork>();
var mockProjectApprovalRepository = new Mock<Repository<ProjectApproval>>();
mockUnitOfWork.Setup(x => x.ProjectApprovalRepository).Returns(mockProjectApprovalRepository.Object);
On this last line I get the error:
Can not instantiate proxy of class: MyNamespace.Repository Could not find a parameterless constructor.
I'm confused by this because I thought the point of Ninject was I didn't need to specify a parameterless constructor. Shouldn't ninject have instantiated a Context and used the constructor with one parameter.
When you do new Mock<Repository<ProjectApproval>>(), you're asking Moq to construct the object. If you asked Ninject to construct it, it would do it.
Ninject doesn't magically step in wherever construction happens - new is still new.
In this case, you can use an overload of the Mock constructor wherein you specify extra args.
Note that its generally accepted that Ninject shouldnt be anywhere near anything remotely close to the any common definition of the term Unit Test.

How to inject with Guice when there are two different constructors?

Total Guice noob here, have read a few articles and seen the intro video, that's about it.
Here's my simplified old code that I'm trying to "guicifiy". Can't quite figure out how to, since (as far as I understand), I can only #inject-annotate one of the two constructors? How can a calling class create the one or the other instance? Or will I have to refactor this somehow?
public class MyDialog extends JDialog {
public MyDialog( JFrame parent, <other parameters...> ) {
super( parent );
}
public MyDialog( JDialog parent, <other parameters...>) {
super( parent );
}
}
You can only inject into the one ctor.
Depending on how this class is being used, you could:
Inject a factory into the client code with two "new" methods.
Roll all the arguments into one ctor and pass null when not required.
How can a calling class create the one or the other instance?
This suggests that the calling classes will want multiple instances of MyDialog? Then you need to use a hand-rolled factory (Assisted Inject can handle this for you if you only had one ctor). I don't know the details of what you are up to and I'm likely repeating what you already know but as a blanked statement I'd suggest also extracting an interface from MyDialog and have the factory return them. This way you can fake MyDialog in tests.
Constructor injection is very clean. mlk is right, saying that you can inject into one constructor only.
What you can do is use method injection:
public class Smt {
private int a;
private Cereal cereal;
private Personality personality;
private ignition;
public Smt() {
this.a = 5;
}
public Smt(int a) {
this.a = a;
}
#Inject
public void setup(#CiniMini Cereal cereal, #Rastafarian Personality personality,
Ignition ignition) {
this.cereal = cereal;
this.personality = personality;
this.ignition = ignition;
}
}
What Guice will do is call your class' setup class method and provide all the injections. Then you do the same thing as in the constructor--assign the objects to your class' attributes.
I agree with the previous comments.
Just an additional hint: constructor injection is supposed to provide all dependencies a class needs. As mlk says, one approach could be to annotate the constructor with most arguments and then refactor the other one to call the former by passing null values where needed.
Additionally, Guice 3.0 supports the so called Constructor Bindings which allow the programmer to specify which constructor to use. See here for more details.

How are you able to Unit Test your controllers without an IoC container?

I'm starting to get into Unit Testing, Dependancy Injection and all that jazz while constructing my latest ASP.NET MVC project.
I'm to the point now where I would like to Unit Test my Controllers and I'm having difficulty figuring out how to appropriately do this without an IoC container.
Take for example a simple controller:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository _repository = new SqlQuestionsRepository();
// ... Continue with various controller actions
}
This class is not very unit testable because of its direct instantiation of SqlQuestionsRepository. So, lets go down the Dependancy Injection route and do:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository _repository;
public QuestionsController(IQuestionsRepository repository)
{
_repository = repository;
}
}
This seems better. I can now easily write unit tests with a mock IQuestionsRepository. However, what is going to instantiate the controller now? Somewhere further up the call chain SqlQuestionRepository is going to have to be instantiated. It seems as through I've simply shifted the problem elsewhere, not gotten rid of it.
Now, I know this is a good example of where an IoC container can help you by wiring up the Controllers dependancies for me while at the same time keeping my controller easily unit testable.
My question is, how is one suppose to do unit testing on things of this nature without an IoC container?
Note: I'm not opposed to IoC containers, and I'll likely go down that road soon. However, I'm curious what the alternative is for people who don't use them.
Isn't it possible to keep the direct instantiation of the field and also provide the setter? In this case you'd only be calling the setter during unit testing. Something like this:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository _repository = new SqlQuestionsRepository();
// Really only called during unit testing...
public QuestionsController(IQuestionsRepository repository)
{
_repository = repository;
}
}
I'm not too familiar with .NET but as a side note in Java this is a common way to refactor existing code to improve the testability. I.E., if you have classes that are already in use and need to modify them so as to improve code coverage without breaking existing functionality.
Our team has done this before, and usually we set the visibility of the setter to package-private and keep the package of the test class the same so that it can call the setter.
You could have a default constructor with your controller that will have some sort of default behavior.
Something like...
public QuestionsController()
: this(new QuestionsRepository())
{
}
That way by default when the controller factory is creating a new instance of the controller it will use the default constructor's behavior. Then in your unit tests you could use a mocking framework to pass in a mock into the other constructor.
One options is to use fakes.
public class FakeQuestionsRepository : IQuestionsRepository {
public FakeQuestionsRepository() { } //simple constructor
//implement the interface, without going to the database
}
[TestFixture] public class QuestionsControllerTest {
[Test] public void should_be_able_to_instantiate_the_controller() {
//setup the scenario
var repository = new FakeQuestionsRepository();
var controller = new QuestionsController(repository);
//assert some things on the controller
}
}
Another options is to use mocks and a mocking framework, which can auto-generate these mocks on the fly.
[TestFixture] public class QuestionsControllerTest {
[Test] public void should_be_able_to_instantiate_the_controller() {
//setup the scenario
var repositoryMock = new Moq.Mock<IQuestionsRepository>();
repositoryMock
.SetupGet(o => o.FirstQuestion)
.Returns(new Question { X = 10 });
//repositoryMock.Object is of type IQuestionsRepository:
var controller = new QuestionsController(repositoryMock.Object);
//assert some things on the controller
}
}
Regarding where all the objects get constructed. In a unit test, you only set up a minimal set of objects: a real object which is under test, and some faked or mocked dependencies which the real object under test requires. For example, the real object under test is an instance of QuestionsController - it has a dependency on IQuestionsRepository, so we give it either a fake IQuestionsRepository like in the first example or a mock IQuestionsRepository like in the second example.
In the real system, however, you set up the whole of the container at the very top level of the software. In a Web application, for example, you set up the container, wiring up all of the interfaces and the implementing classes, in GlobalApplication.Application_Start.
I'm expanding on Peter's answer a bit.
In applications with a lot of entity types, it is not uncommon for a controller to require references to multiple repositories, services, whatever. I find it tedious to manually pass all those dependencies in my test code (especially since a given test may only involve one or two of them). In those scenarios, I prefer setter-injection style IOC over constructor injection. The pattern I use it this:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository Repository
{
get { return _repo ?? (_repo = IoC.GetInstance<IQuestionsRepository>()); }
set { _repo = value; }
}
private IQuestionsRepository _repo;
// Don't need anything fancy in the ctor
public QuestionsController()
{
}
}
Replace IoC.GetInstance<> with whatever syntax your particular IOC framework uses.
In production use nothing will invoke the property setter, so the first time the getter is called the controller will call out to your IOC framework, get an instance, and store it.
In test, you just need to call the setter prior to invoking any controller methods:
var controller = new QuestionsController {
Repository = MakeANewMockHoweverYouNormallyDo(...);
}
The benefits of this approach, IMHO:
Still takes advantage of IOC in production.
Easier to manually construct your controllers during testing. You only need to initialize the dependencies your test will actually use.
Possible to create test-specific IOC configurations, if you don't want to manually configure common dependencies.

Resources