微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在创建Object时注入属性

我有一个LoggedTextWriter,我想将其注入 LinqTosql DataContext类的Log属性.

我的自定义LoggedTextWriter有一个构造函数,它接受ICustomWriter,但我不知道如何将它注入到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绑定,上下文(x下面)传递给你的lambda.您可以使用它来查找内核并查找您的日志.这与AutoFac和Funq的工作方式非常相似.此外,transient是认范围,因此如果您愿意,可以将其从绑定中删除.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐