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"] }; NinjectKernel.Bind<IProductsRepository>(). To<ProductsRepository>(). 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; } }
Pass constructor arguments with Ninject dependency injector
How to plan CCSP Exam preparation
Develop a MongoDB pipeline to transform data into time buckets
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2025 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use