我有一个 LoggedTextWriter,我想将它注入(inject)到 LinqToSql DataContext 类的 Log 属性中。

我的自定义 LoggedTextWriter 有一个采用 ICustomWriter 的构造函数,但我不知道如何将它注入(inject)到 Log 属性中。

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

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

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

最佳答案

像这样!使用 ToMethod 绑定(bind),上下文(x 下面)被传递给你的 lambda。您可以使用它来查找内核并找到您的日志。这与 AutoFac 和 Funq 的工作方式非常相似。此外,transient 是默认范围,因此您可以根据需要将其从绑定(bind)中删除。

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>()
    });

关于c# - 创建对象时注入(inject)属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4022724/

10-11 04:14
查看更多