Shawn Mclean
Shawn Mclean

Reputation: 57469

Injecting a dependency through a method parameter

I did all the bindings already. My problem now is getting the final binding to work on a static method property.

For eg:

Bind<IUserService>().To<UserService>();
Bind<IUserRepository>().To<SqlServerUserRepository>().InRequestScope();

Bind<IDatabaseInitializer<EconoDb>>().To<DatabaseInitializer>();
//Problem here. How do I inject the user service here?
DbDatabase.SetInitializer(/*IDatabaseInitializer goes here */);

Upvotes: 0

Views: 231

Answers (2)

Daniel Marbach
Daniel Marbach

Reputation: 2314

Hy You can use OnActivation.

Bind<IUserService>().To<UserService>();
Bind<IUserRepository>().To<SqlServerUserRepository>().InRequestScope();

Bind<IDatabaseInitializer<EconoDb>>().To<DatabaseInitializer>()
.OnActivation(initializer => DbDatabase.SetInitializer(initializer));

or the short version

Bind<IDatabaseInitializer<EconoDb>>().To<DatabaseInitializer>()
.OnActivation(DbDatabase.SetInitializer);

Upvotes: 1

Matthew Abbott
Matthew Abbott

Reputation: 61589

If your DatabaseInitializer accepts the IUserService constructor parameter, you can use Ninject to resolve the instance:

var initializer = kernel.Get<IDatabaseInitializer<EconoDb>>()
DbDatabase.SetInitializer(initializer);

Entity Framework doesn't have any out of the box support for DI through an IoC/SL (as far as I am aware) which means you'll have to handle passing that value to the DbDatabase.SetInitializer call yourself.

Upvotes: 1

Related Questions