加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:11:52 所属栏目:百科 来源:网络整理
导读:我有一个LoggedTextWriter,我想将其注入 LinqToSql DataContext类的Log属性. 我的自定义LoggedTextWriter有一个构造函数,它接受ICustomWriter,但我不知道如何将它注入到Log属性中. BindDataContext() .ToSelf() .InTransientScope() .WithConstructorArgumen
我有一个LoggedTextWriter,我想将其注入 LinqToSql DataContext类的Log属性.

我的自定义LoggedTextWriter有一个构造函数,它接受ICustomWriter,但我不知道如何将它注入到Log属性中.

Bind<DataContext>()
                .ToSelf()
                .InTransientScope()
                .WithConstructorArgument("connection",@"Data Source=localhostsqlexpress2008;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=localhostsqlexpress2008;Initial Catalog=MyDB;Integrated Security=True")
    {
        ObjectTrackingEnabled = true,Log = x.Kernel.Get<LoggedTextWriter>()
    });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读