How to pass arguments to constructor with Ninject dependency injector

When using dependency injection, some time we need to pass additional parameters in constructor of that object. Ninject provides a very handy method that you can use to pass arguments when you bind the interfaces. I have a similar situation in my shopping web site. I uses MVC framework. It has an interface for repository component of the web site. One of the repository used in the application is Amazon web service. Each amazon web service needs to be associated with some identity parameters. The class that implements repository for amazon web service requires that caller passes identity parameters. You could argue that why this parameter is not a dependency as well so I could use binding for it. The problem is that it is hard to come up with a unified identity interface for each type of b2b web services. Therefore it made sense that each repository will handle this identity parameters on its own.

The following code shows how WithConstructorArgument method is used to pass parameters to constructor when Ninject creates instance of the object.

private void AddBindings()
   RequestIdentity identity = new RequestIdentity()
      AssociateTag = ConfigurationManager.AppSettings["awsassociatetag"],
      AccessKey = ConfigurationManager.AppSettings["awsaccesskey"],
      SecretKey = ConfigurationManager.AppSettings["awssecretkey"]
    WithConstructorArgument("identity", identity);

Following code shows ProductRepository class implementation that is expecting the parameter to be passed to it.

public class ProductsRepository : IProductsRepository
     private RequestIdentity Identity { get; set; }
     public ProductsRepository(RequestIdentity identity)
        if (null == identity)
            throw new ArgumentNullException("identity");
        Identity = identity;
comments powered by Disqus

Blog Tags