Default values for constructor arguments in a library project - dependency-injection

I am writing a library that will provide a collection of public types to its consumers.
I want to make types from this library dependency injection friendly. This means that every class needs to have a constructor through which it is possible to specify every single dependency of the object being initialized. I also want the library to adhere to the convention over configuration principle. This means that if a consumer wants the default behavior, he may use a parameterless constructor and the object will somehow construct the dependencies for itself.
In example (C#):
public class Samurai {
private readonly IWeapon _weapon;
// consumers will use this constructor most of the time
public Samurai() {
_weapon = ??? // get an instance of the default weapon somehow
}
// consumers will use this constructor if they want to explicitly
// configure dependencies for this instance
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
}
My first solution would be to use the service locator pattern.
The code would look like this:
...
public Samurai() {
_weapon = ServiceLocator.Instance.Get<IWeapon>();
}
...
I have a problem with this, though. Service locator has been flagged as an anti-pattern (link) and I completely agree with these arguments. On the other hand, Martin Fowler advocates use of the service locator pattern exactly in this situation (library projects) (link). I want to be careful and eliminate the possible necessity to rewrite the library after it shows up that service locator really was a bad idea.
So in conclusion - do you think that service locator is fine in this scenario? Should I solve my problem in a completely different way? Any thought is welcome...

If you want to make life easier for users who are not using a DI container, you can provide default instances via a dedicated Defaults class which has methods like this:
public virtual Samurai CreateDefaultSamurai()
{
return new Samurai(CreateDefaultWeapon());
}
public virtual IWeapon CreateDefaultWeapon()
{
return new Shuriken();
}
This way you don't need to pollute the classes themselves with default constructors, and your users aren't at risk of using those default constructors unintentionally.

There is an alternative, that is injecting a specific provider, let's say a WeaponProvider in your case into your class so it can do the lookup for you:
public interface IWeaponProvider
{
IWeapon GetWeapon();
}
public class Samurai
{
private readonly IWeapon _weapon;
public Samurai(IWeaponProvider provider)
{
_weapon = provider.GetWeapon();
}
}
Now you can provide a local default provider for a weapon:
public class DefaultWeaponProvider : IWeaponProvider
{
public IWeapon GetWeapon()
{
return new Sword();
}
}
And since this is a local default (as opposed to one from a different assembly, so it's not a "bastard injection"), you can use it as part of your Samurai class as well:
public class Samurai
{
private readonly IWeapon _weapon;
public Samurai() : this(new DefaultWeaponProvider())
{
}
public Samurai(IWeaponProvider provider)
{
_weapon = provider.GetWeapon();
}
}

I have used the following approach in my C# project. The goal was to achieve dependency injection (for unit / mock testing) whilst not crippling the implementation of the code for a "normal use case" (i.e. having a large amount of new()'s that are cascaded through the execution flow).
public sealed class QueueProcessor : IQueueProcessor
{
private IVbfInventory vbfInventory;
private IVbfRetryList vbfRetryList;
public QueueProcessor(IVbfInventory vbfInventory = null, IVbfRetryList vbfRetryList = null)
{
this.vbfInventory = vbfInventory ?? new VbfInventory();
this.vbfRetryList = vbfRetryList ?? new VbfRetryList();
}
}
This allows DI but also means any consumer doesn't have to worry about what the "default instance flow" should be.

Related

How to implement UnitOfWork with Onion Architecture without introducing dependencies?

I am setting up an asp.Net Mvc 4 app and looking to configure it using the Onion Architecture Pattern.
In the past I have used the Unit of Work Pattern like this
public class UnitOfWork : IUnitOfWork, IDisposable
{
private IRepository<CallModel> _callRepo;
private IRepository<UserModel> _userRepo;
public IRepository<CallModel> CallRepo
{
get
{
if (_callRepo == null)
{
_callRepo = new Repository<CallModel>();
}
return _callRepo;
}
}
public IRepository<UserModel> UserRepo
{
get
{
if (_userRepo == null)
{
_userRepo = new Repository<UserModel>();
}
return _userRepo;
}
}
}
I would then pass the instance of the UnitOfWork Class to the Controller to do simple CRUD stuff like this.
public class QuestionsController : Controller
{
private IUnitOfWork _unitOfWork;
[Inject]
public QuestionsController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
I have seperated the app into three projects.
Core
Infrastructure
Web
I have my Interfaces all in the Core project and the implementation of the IRepository interface in the Infrastructure project.
If I put the UnitOfWork Class in the Core Project then since it calls for a new Repository in the Infrastructure project I am creating a dependency from the Core to the Infrastructure.
If I include it in the Infrastructure then the Web project (which has the controllers) will have a dependency on the Infrastructure and the whole Solution ends up looking less like an Onion and more like spaghetti.
I have my Interfaces all in the Core project and the implementation of the IRepository interface in the Infrastructure project. If I put the UnitOfWork Class in the Core Project then since it calls for a new Repository in the Infrastructure project I am creating a dependency from the Core to the Infrastructure.
Hmm, not really. Your unit of work class should have a dependency on IRepository, not the Repository implementation itself. If you are using Dependency Injection, this should not pose a problem, as it should find the right type and provide it at runtime. I'm not sure whether the Onion architecture is even possible without using DI.
See david.s's answer as well, as this is exactly how I set things up--have a project for the sole purpose of wiring up dependencies.
What I do is have another project named DependencyResolution which has references to Core and Infrastructure an where I configure my IoC container. Then I can refence only DependencyResolution from the Web project.
I would do like david.s create project named DependencyResolution but let it referance Web, Core and Infrastructure.
In that project you could do:
[assembly: PreApplicationStartMethod(typeof(Start), "Register")]
namespace DependencyResolution
{
public static class Start
{
public static void Register()
{
UnityConfig.Register();
}
}
}
and to register DI.
namespace DependencyResolution
{
public static class UnityConfig
{
public static void Register()
{
DependencyResolver.SetResolver(new UnityDependencyResolver());
}
}
}
So no referance between Web and infrastructure is needed.
Best regards
For what it's still worth, I have implemented my own library that applies the UnitOfWork-pattern a little differently than I've seen in any code sample before, but I have found it to work very well in practice. In short: I kinda copied the way .NET Transactions work by creating a scope and then enlisting resources in the ambient unitofwork(-manager) where necessary. What basically happens is that when a new message/request is being handled, this code is executed:
public void Handle<TMessage>(TMessage message)
{
using (var scope = CreateMessageProcessorContextScope())
{
HandleMessage(message);
scope.Complete();
}
}
Now just as with transactions, as soon as the Thread is still inside the scope, an ambient UnitOfWork-controller is present in which all resources that are used and changed during the request can enlist dynamically. They do this by implementing the IUnitOfWork-interface that has two methods:
public interface IUnitOfWork
{
bool RequiresFlush();
void Flush();
}
Instances that implement this interface can then enlist themselves as follows:
MessageProcessorContext.Current.Enlist(this);
Typically, a Repository-class will implement this interface, and when it detects it's managed aggregates are changed/added/removed, it can enlist itself (double enlistments are ignored).
In my case, the framework assumes that you are using an IOC-framework that will resolve all message-handlers and repositories for you, so I made enlistment to the ambient unit of work controller easier by letting it inject an instance of the current IUnitOfWorkManager into the constructor where required. This way the dependencies of the unit of work manager and the actual pieces that require to be flushed (repositories, services, etc) are reversed:
internal sealed class OrderRepository : IOrderRepository, IUnitOfWork
{
private readonly IUnitOfWorkManager _manager;
private readonly Dictionary<Guid, Order> _orders;
public OrderRepository(IUnitOfWorkManager manager)
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
_manager = manager;
}
bool IUnitOfWork.RequiresFlush()
{
return _orders.Values.Any(order => order.HasChanges());
}
void IUnitOfWork.Flush()
{
// Flush here...
}
public void Add(Order order)
{
_orders.Add(order.Id, order);
_manager.Enlist(this);
}
}
As soon as a request has been handled succesfully (no exceptions thrown), scope.Complete() will be called which triggers the controller to check with all enlisted items whether they (still) need to be flushed (by calling RequiresFlush()), and if so, flushes them (by calling Flush()).
All in all, this allows for a very maintainable solution (in my perspective) in which new repositories and other dependencies can be added on the fly without changing any master unitofwork class, just like the TransactionManager doesn't need to know upfront which items may take part in any given Transaction.

How do I tell MEF to instantiate a single object for a given type per application?

Lets say I have a class called FooController in which I have a property called Bar of type IBar (interface). I need to initialize Bar via MEF. However I need MEF to create only one instance of IBar type for the duration of the application (despite multiple calls to initialize it due to multiple requests) and make it available to all requests concurrently. Note that IBar implementations can be assumed thread safe.
i.e.
public interface IBar
{
string Method();
}
[Export(typeof(IBar))]
public class MyBar: IBar
{
public string dateTimeCreated;
public MyBar()
{
System.Threading.Thread.Sleep(1000);
dateTimeCreated = DateTime.Now.ToLongTimeString() + " ";
}
public string Method()
{
return dateTimeCreated;
}
}
public class FooController : ApiController
{
[Import(typeof(IBar), RequiredCreationPolicy = CreationPolicy.Shared)]
public IBar Bar { get; set; }
public FooController()
{
//Assume CompositionContainer.ComposeParts call here
}
public string Get()
{
return Bar.Method();
}
}
The problem is each time I call Get() on FooController, the returned time value changes. This means the MyBar object is being reinstantiated for each call. I basically need it to return the same value meaning I need to tell MEF to create only one instance of IBar in my application despite multiple requests.
Thanks in advance.
You need to specify the PartCreationPolicy attribute on your MyBar export. Like this:
[Export(typeof(IBar))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MyBar : IBar
{
// ...
}
That also means that you don't need to specify the creation policy on your import:
[Import]
public IBar Bar { get; set; }
The ASP.NET MVC integration of MEF interprets CreationPolicy.Any and CreationPolicy.Shared as single instance per HTTP request. You need to apply the ApplicationShared attribute to the part to share it between HTTP requests.
Update:
The ApplicationSharedAttribute can be found in the System.ComponentModel.Composition.Web.Mvc assembly. Unfortunately this is not distributed with Framework 4.5. It can be found at the Using MEF with ASP.NET MVC 3 Sample Code example in the lib folder. The drawback is that you will have to reference the composition assemblies found it that sample and not the latest ones.
If you do not want to do that then start with this very simple approach:
Add a CompositionContainer in your MvcApplication class as a public property.
On the MvcApplication constructor create the container and add some catalogs.
On the controller get the application from the HttpContext and use one of the GetExport/GetExportedValue/GetExportedValues methods of the CompositionContainer. No need to call ComposeParts on the container.
There are a lot of other approaches that are more elaborate but this should get you started.

Multiple dependencies in an asp.net mvc controller constructor injected

In my asp.net mvc controller`s constructor I have multiple (5) interfaces which communicate with my database in this way:
[HttpGet]
public ActionResult Create()
{
var releases = _releaseDataProvider.GetReleases();
var templates = _templateDataProvider.GetTemplates();
var createTestplanViewModel = new CreateTestplanViewModel(templates, releases);
return PartialView(createTestplanViewModel);
}
Above I use 2 different interfaces to get data from the database.
business case: To create a testplan I need to show the user the available releases + templates he can choose from.
How can I decrease the dependency/over-injection of these 2 interfaces
In the MVC project:
public class MyController : Controller
{
private readonly IQueryProcessor _queryProcessor;
public MyController(IQueryProcessor queryProcessor)
{
_queryProcessor = queryProcessor;
}
[HttpGet]
public ActionResult Create()
{
var releases = _queryProcessor.Execute(new ProvideReleaseData());
var templates = _queryProcessor.Execute(new ProvideTemplateData());
var createTestplanViewModel = AutoMapper.Mapper
.Map<CreateTestplanViewModel>(releases);
AutoMapper.Mapper.Map(templates, createTestplanViewModel);
return PartialView(createTestplanViewModel);
}
}
You can then constructor inject your current provider implementations into IQueryHandler implementations. The IQueryProcessor is just infrastructure. See this for more info: https://cuttingedge.it/blogs/steven/pivot/entry.php?id=92
Reply to comments:
It's at the site I linked to. Here's mine:
using System.Diagnostics;
using SimpleInjector;
namespace MyApp.Infrastructure
{
sealed class SimpleQueryProcessor : IQueryProcessor
{
private readonly Container _container;
public SimpleQueryProcessor(Container container)
{
_container = container;
}
[DebuggerStepThrough]
public TResult Execute<TResult>(IDefineQuery<TResult> query)
{
var handlerType = typeof(IHandleQueries<,>)
.MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = _container.GetInstance(handlerType);
return handler.Handle((dynamic)query);
}
}
}
A good general way to decouple your database would be using a unit of work. Here's a great article on from asp.net, as well as another article on MSDN.
In summary, you create a single unit where all of your database/service calls reside and it can handle the database logic. This would reduce the dependancy of your multiple interfaces into a single point, so you would only need to inject 1 class into your controller.
A quote from the MSDN article:
According to Martin Fowler, the Unit of Work pattern "maintains a list
of objects affected by a business transaction and coordinates the
writing out of changes and the resolution of concurrency problems."
EDIT
It seems to me you basically have these options to reduce constructor dependency count here:
Split the controller
Add layer in front of the two interfaces
Switch to property injection
Service locator
#3 and #4 are included for good measure, but they obviously don't actually decrease the dependency count, they only hide them from the constructor. They also have several disadvantages, and I consider service locator especially evil most of the time.
For #1, if you feel your constructor is actually doing two+ jobs, and there is a clean separation where you could split, I would do so. I assume from your responses that you have already considered this, however, and don't want to do this.
That leaves #2 - adding another layer. In this case that would be introducing a factory interface for that particular view model. Naively, I'll name this ICreateTestplanViewModelFactory, but you can name it something more sensical for your app if you wish. A single method on it would construct a CreateTestplanViewModel.
This makes the fact that the data for this view is coming from 2 sources merely an implementation detail. You would wire up an implementation which takes IReleaseDataProvider and ITemplateDataProvider as constructor dependencies.
This is along the lines of what I was suggesting:
public interface IProvideTestPlanSetupModel
{
CreateTestplanViewModel GetModel();
}
public class TestPlanSetupProvider : IProvideTestPlanSetupModel
{
private readonly IReleaseDataProvider _releaseDataProvider;
private readonly ITemplateDataProvider _templateDataProvider;
public TestPlanSetupProvider(IReleaseDataProvider releaseDataProvider, ITemplateDataProvider templateDataProvider)
{
_releaseDataProvider = releaseDataProvider;
_templateDataProvider = templateDataProvider;
}
public CreateTestplanViewModel GetModel()
{
var releases = _releaseDataProvider.GetReleases();
var templates = _templateDataProvider.GetTemplates();
return new CreateTestplanViewModel(releases, templates);
}
}
public class TestPlanController : Controller
{
private readonly IProvideTestPlanSetupModel _testPlanSetupProvider;
public TestPlanController(IProvideTestPlanSetupModel testPlanSetupProvider)
{
_testPlanSetupProvider = testPlanSetupProvider;
}
[HttpGet]
public ActionResult Create()
{
var createTestplanViewModel = _testPlanSetupProvider.GetModel();
return PartialView(createTestplanViewModel);
}
}
If you don't like constructing a view model anywhere outside the controller, the interface could provide an intermediate object with the same properties that you would copy to the view model. But that is silly, as this combination of data is only relevant for that particular view, which is precisely what the view model is supposed to represent.
On a side note, it seems you are running into pretty common annoyances doing read/write through the same model. Since these issues bother you so, you might investigate CQRS, which perhaps would make you feel less dirty about talking to the database directly for these types of queries and would help you get around the layering labyrinth we all enjoy so much. It seems promising, though I have not yet had the pleasure of test driving it in a production application.

Creating objects with dependencies - dependency injection

Let's say we have class:
public class WithDependencies
{
public WithDependencies(IAmDependencyOne first, IAmDependencyTwo second)
// ...
}
Now the question. How do you create objects of WithDependencies class in an application?
I know there are many ways.
new WithDependencies(new DependencyOne(), new DependencyTwo());
new WithDependencies(IoC.Resolve(IDependencyOne), IoC.Resolve(IDependencyTwo());
// register IDependencyOne, IDependencyTwo implementations at app start
IoC.Resolve(WithDependencies);
// register IDependencyOne, IDependencyTwo implementations at app start
// isolate ourselves from concrete IoC Container
MyCustomWithDependenciesFactory.Create();
and so on...
What do you think is the way to do it?
Edit:
Because I don't get answers or I don't understand them I'll try to ask again. Let's say that on some event (button, timer, whatever) I need new object WithDependencies(). How do I create it? Assume IoC container is already configured.
It depends on the context, so it's impossible to provide a single answer. Conceptually you'd be doing something like this from the Composition Root:
var wd = new WithDependencies(new DependencyOne(), new DependencyTwo());
However, even in the absence of a DI Container, the above code isn't always unambiguously the correct answer. In some cases, you might want to share the same dependency among several consumers, like this:
var dep1 = new DependencyOne();
var wd = new WithDependencies(dep1, new DependencyTwo());
var another = AnotherWithDependencies(dep1, new DependencyThree());
In other cases, you might not want to share dependencies, in which case the first option is more correct.
This is just a small glimpse of an entire dimension of DI concerned with Lifetime Management. Many DI Containers can take care of that for you, which is one excellent argument to prefer a DI Container over Poor Man's DI.
Once you start using a DI Container, you should follow the Register Resolve Release pattern when resolving types, letting Auto-wiring take care of the actual composition:
var wd = container.Resolve<WithDependencies>();
The above example assumes that the container is already correctly configured.
If you need to create a dependency which has its own dependencies, you can either A) do it yourself, or B) ask something else to do it for you. Option A negates the benefits of dependency injection (decoupling, etc.), so I would say option B is a better starting point. Now, we have chosen to use the factory pattern, no matter whether it takes the form of a service locator (i.e. IoC.Resolve), a static factory, or an instance factory. The point is that we have delegated that responsibility to an external authority.
There are a number of trade-offs required for static accessors. (I went over them in another answer, so I won't repeat them here.) In order to avoid introducing a dependency on the infrastructure or the container, a solid option is to accept a factory for creating WithDependencies when we need an instance somewhere else:
public class NeedsWithDependencies
{
private readonly IWithDependenciesFactory _withDependenciesFactory;
public NeedsWithDependencies(IWithDependenciesFactory withDependenciesFactory)
{
_withDependenciesFactory = withDependenciesFactory;
}
public void Foo()
{
var withDependencies = _withDependenciesFactory.Create();
...Use the instance...
}
}
Next, we can create a container-specific implementation of the factory:
public class WithDependenciesFactory : IWithDependenciesFactory
{
private readonly IContainer _container;
public WithDependenciesFactory(IContainer container)
{
_container = container
}
public WithDependencies Create()
{
return _container.Resolve<WithDependencies>();
}
}
Now NeedsWithDependencies is completely isolated from any knowledge of how WithDependencies gets created; it also exposes all its dependencies in its constructor, instead of hiding dependencies on static accessors, making it easy to reuse and test.
Defining all those factories can get a little cumbersome, though. I like Autofac's factory relationship type, which will detect parameters of the form Func<TDependency> and automatically inject a function which serves the same purpose as the hand-coded factory above:
public class NeedsWithDependencies
{
private readonly Func<WithDependencies> _withDependenciesFactory;
public NeedsWithDependencies(Func<WithDependencies> withDependenciesFactory)
{
_withDependenciesFactory = withDependenciesFactory;
}
public void Foo()
{
var withDependencies = _withDependenciesFactory();
...Use the instance...
}
}
It also works great with runtime parameters:
public class NeedsWithDependencies
{
private readonly Func<int, WithDependencies> _withDependenciesFactory;
public NeedsWithDependencies(Func<int, WithDependencies> withDependenciesFactory)
{
_withDependenciesFactory = withDependenciesFactory;
}
public void Foo(int x)
{
var withDependencies = _withDependenciesFactory(x);
...Use the instance...
}
}
Sometimes I try to get rid of factories or at least not depend directly on them, so Dependency Injection (without factories) is useful of course.
Therefore I use Google Juice, cause its a small little framework using Java Annotations and you can quickly change your injections / dependencies. Just take a look at it:
http://code.google.com/p/google-guice/

Ninject 2.0: Property Injection without attribute

Is there a way to use Property Injection in Ninject 2 without using the [Inject] attribute? This creates a dependency to Ninject in the class that will be wired using it and I prefer to avoid having unneeded dependencies to my IoC container, that's why I end up using Constructor Injection more often.
I guess the same applies to Method Injection
I followed Ruben's tip and posted a small blog post on how to achieve this, but here's the quick answer:
Create a custom attribute:
public class InjectHereAttribute : Attribute
{
}
The target class will now look like this:
public class Samurai
{
[InjectHere]
public IWeapon Context { get; set; }
}
Now Ninject must be configured to use the custom attribute, this can be done by creating an implementation of IInjectionHeuristic that recognizes the custom attribute:
public class CustomInjectionHeuristic : NinjectComponent, IInjectionHeuristic, INinjectComponent, IDisposable
{
public new bool ShouldInject(MemberInfo member)
{
return member.IsDefined(
typeof(InjectHereAttribute),
true);
}
}
And finally add this behavior to the Ninject Kernel using the Components collection, it will run along the existing components, namely the default implementation of IInjectionHeuristic, which means either the default or the custom attribute can be used.
// Add custom inject heuristic
kernel.Components.Add<IInjectionHeuristic, CustomInjectionHeuristic>();
You can pass in another [attribute] type to the Kernel upon creation which can be used instead of InjectAttribute, but you'll still have to reference something centrally OOTB.
There was a similar question very recently about doing PI without attributes - there's no OOTB (as in directly on the fluent configuration interface) to put in a custom scanner but the extensibility points (you add a component that implements a Ninject interface as you build your Kernel that dictates how that aspect is to be work if looking for a given attribute isnt't what you want) are in there to determine where to inject based on Convention over Configuration - there's nothing stopping you amending the scanning to be based on just an attribute name (so it doesnt necessarily have to live in a central location).
Note that, in general, constructor injection is good for lots of reasons anyway, including this one, and keeping you code container agnostic is important (even if you're currently happy with one!)
I was able to accomplish this using a Heuristic class:
public sealed class MyInjectionHeuristic : NinjectComponent, IInjectionHeuristic
{
private static readonly IList<Type>
_propertyInjectible =
new List<Type>
{
typeof(IMyService),
};
/// <summary>
/// Returns a value indicating whether the specified member should be injected.
/// </summary>
/// <param name="member">The member in question.</param>
/// <returns><c>True</c> if the member should be injected; otherwise <c>false</c>.</returns>
public bool ShouldInject(MemberInfo member)
{
var info = member as PropertyInfo;
if( member == null || info == null )
return false;
if (info.CanWrite)
return _propertyInjectible.Contains(info.PropertyType);
if( this.Settings == null )
return false;
var propList = member.GetCustomAttributes(this.Settings.InjectAttribute, true);
return propList.Length > 0;
}
}
When creating your kernel:
var heuristics = _kernel.Components.Get<ISelector>().InjectionHeuristics;
heuristics.Add(new MyInjectionHeuristic());
Simple add additional types to the IList when you want to inject other types via properties.

Resources