Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle Windsor register class with constructor parameters

I have the following class:

public class DatabaseFactory<C> : Disposable, IDatabaseFactory<C> where C : DbContext, BaseContext, new() {     private C dataContext;     private string connectionString;      public DatabaseFactory(string connectionString)     {         this.connectionString = connectionString;     }      public C Get()     {         return dataContext ?? (dataContext = Activator.CreateInstance(typeof(C), new object[] {connectionString}) as C);     }      protected override void DisposeCore()     {         if (dataContext != null)             dataContext.Dispose();     } } 

When I try to start the web api, I get the following error:

Can't create component 'MyApp.DAL.Implementations.DatabaseFactory'1' as it has dependencies to be satisfied. 'MyApp.DAL.Implementations.DatabaseFactory'1' is waiting for the following dependencies: - Parameter 'connectionString' which was not provided. Did you forget to set the dependency?

How do I register it correctly and how do I pass the parameter at runtime?

like image 742
Ivan-Mark Debono Avatar asked Nov 27 '13 13:11

Ivan-Mark Debono


1 Answers

You need to register the constructor parameter:

container.Register(     Component.For<IDatabaseFactory>().ImplementedBy<DatabaseFactory>()              .DependsOn(Dependency.OnValue("connectionString", connectionString))     ); 
like image 106
Ufuk Hacıoğulları Avatar answered Sep 20 '22 13:09

Ufuk Hacıoğulları