开发者

Injecting a property when creating a Object

I have a LoggedTextWriter that I'd like to inject in to the Log property of the LinqToSql DataContext class.

My custom LoggedTextWriter has a constructor that takes ICustomWriter, but I don't know how to inject it in to the Log property.

Bind<DataContext>()
                .ToSelf()
                .InTransientScope()
                .WithConstructorArgument("connection", @"Data Source=localhost\sqlexpress2008;Initial Catalog=MyDB;Integrated Security=True")
                .WithPropertyValue("ObjectTrackingEnabled", true)
                .WithPropertyValue("Log",开发者_Go百科 **<HowDoIGetAnInstanceOfLoggedTextWriter>**);

Bind<LoggedTextWriter>().ToSelf().InTransientScope();

Bind<ICustomWriter>().To<MyCustomWriter>().InTransientScope();


Like this! Bind using ToMethod, the context (x below) is passed to your lambda. You can use it to lookup the Kernel and find your log. This is very similar to how AutoFac and Funq work. Also, transient is the default scope, so you can remove it from your bindings if you'd like.

Bind<LoggedTextWriter>().ToSelf();

Bind<ICustomWriter>().To<MyCustomWriter>();

Bind<DataContext>().ToMethod(x => 
    new DataContext(@"Data Source=localhost\sqlexpress2008;Initial Catalog=MyDB;Integrated Security=True")
    {
        ObjectTrackingEnabled = true,
        Log = x.Kernel.Get<LoggedTextWriter>()
    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜