[英]Property of one class is passed as parameter to constructor of another class. How to resolve this with Autofac?
我是 Autofac 的新手,这是我的问题的场景:
我有 2 个班级,他们都是单身人士。
其中一个有一些公共财产,例如。
public class ClassWithProperty
{
public string SomeProperty { get; set; }
}
第二个 class 有一个构造函数,它应该将第一个 class 的属性作为参数:
public class ClassWithConstructor
{
private string _someParameter;
public ClassWithConstructor(string someParameter)
{
_someParameter = someParameter;
}
}
没有 Autofac 我可以这样做:
var classWithProperty = new ClassWithProperty();
var classWithConstructor = new ClassWithConstructor(classWithProperty.SomeProperty);
我无法使用 Autofac 解决此问题,也无法在此处或谷歌中找到任何解决方案。 我所做的:
var builder = new ContainerBuilder();
builder.RegisterType<ClassWithProperty>().InstancePerLifetimeScope();
builder.RegisterType<ClassWithConstructor>()
.WithParameter() // what should be done here to pass exactly ClassWithProperty.SomeProperty here?
.InstancePerLifetimeScope();
var container = builder.Build();
当然,这是为了显示我的问题而简化的场景。 在实际场景中,我将 TreeList 从一个表单传递到另一个视图 class 并在该 TreeList 上工作。
您可以注册一个 lambda 来手动构造您的ClassWithConstructor
var builder = new ContainerBuilder();
builder.RegisterType<ClassWithProperty>()
.InstancePerLifetimeScope();
builder.Register(c => new ClassWithConstructor(c.Resolve<ClassWithProperty>().SomeProperty))
.InstancePerLifetimeScope();
或者
var builder = new ContainerBuilder();
builder.RegisterType<ClassWithProperty>()
.InstancePerLifetimeScope();
builder.Register<ClassWithConstructor>()
.WithParameter(new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "someParameter",
(pi, ctx) => "sectionName"))
.InstancePerLifetimeScope();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.