This project is read-only.

Pick & choose your constructor arguments with Unity

The Unity configuration engine is somewhat limited. One example is what you have to do in order to specify constructor arguments.

Consider the following skeleton of a class definition

public class CustomerRepository
{
  public CustomerRepository(string connectionString, ILog log, ISomethingElse else) { ... }
}

With Unity's API registering the connectionString parameter would look like this

container.RegisterType<ICustomerRepository, CustomerRepository>(new InjectionConstructor("I'mAConnectionString", typeof(ILog), typeof(ISomethingElse)));

Now this is intuitive isn't it? A couple of questions came to my mind when I first had a look at this
  • Why do I have to write so much code?
  • Why do I have to dive so deep into the implementation of Unity?
  • Why do I have to know about the InjectionConstructor class?
  • Or that I have to provide all parameters in the correct order?
  • Who wants to find out that you can provide placeholders for parameters (typeof(Xyz)) that Unity will deal with?
  • Why don't they give you a decent DSL for configuration?

With the ConfigurationBuilder API the code could look as simple as that

var builder = new ConfigurationBuilder();
builder.For<ICustomerRepository>().Use<CustomerRepository>().Ctor(x => x.With("I'mAConnectionString"));

Map from abstraction to implementation and when you determine which constructor to use please do your magic and use my connectionString as well. Thank you.

A couple of simple conventions are applied and you are done.

See the TecX.Unity.Configuration and TecX.Unity sources for implementation details.

Last edited Feb 6, 2012 at 9:10 AM by weberse, version 1

Comments

No comments yet.