开发者

How do I retrieve objects in Ninject kernel parameters that need in constructor for initialization

开发者 https://www.devze.com 2023-02-12 03:35 出处:网络
I\'m using as Ninject IoC. My question is how to retrieve an object that requires a parameter in the constructor.

I'm using as Ninject IoC.

My question is how to retrieve an object that requires a parameter in the constructor.

Below a sample code:

//Interface for connection
public interface IConnection
{
    IDbConnection CurrentConnection { get; }
}

//Concret co开发者_运维技巧nnection
public class MyConnection : IConnection
{
    public MyConnection(IDbConnection nativeConnection){  }
}

//Module ninject
class Module : NinjectModule
{
    public override void Load()
    {
        Bind<IConnection>().To<MyConnection>().InSingletonScope();
    }
}

//Native connection
var sqlConn = new SqlCeConnection();

//Ninject kernel
var ker = new StandardKernel(new Module());
return ker.Get<IConnection>(); //How can I pass as parameters to the constructor of class "MyConnection"??


You have to add/define a binding for IDbConnection. Then Ninject will pass that automatically to the constructor. For example

Bind<IDbConnection>.To<SqlCeConnection>();

Or you can have a constant in your module

private static readonly SqlConnection = new SqlCeConnection();

And then bind the interface to that

Bind<IDbConnection>.ToConstant(SqlConnection);

Best check this page for more information.

Update

I don't think it's a very sophisticated design. But if you want you can directly pass a parameter to the constructor.

ker.Get<IConnection>(new ConstructorArgument("nativeConnection",yourConnection));

I don't know why exactly you need that, and how it works in singleton scope though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号