c# - 一个类的属性作为参数传递给另一个类的构造函数。如何用 Autofac 解决这个问题?
问题描述
我是 Autofac 的新手,这是我的问题的场景:
我有 2 个班级,他们都是单身人士。
其中一个有一些公共财产,例如。
public class ClassWithProperty
{
public string SomeProperty { get; set; }
}
第二类有一个构造函数,它应该将第一类的属性作为参数:
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 从一个表单传递到另一个视图类,并完全在该 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();
推荐阅读
- metapost - 在 Metapost 中沿路径改变 Pennib
- javascript - 如何在功能组件中计算 React Native 中选中的复选框?
- python - 如何从 Tensorflow 获取 CNN 模型的架构师
- spring-boot - 在 Kubernetes 中创建的服务帐户能够访问其他命名空间中的所有资源吗?
- express - Axios(客户端)+ Express(后端):如何在客户端向后端执行“GET”请求时正确传输参数?
- android - 为什么 Android Studio 退出但我尝试编写代码或编辑布局文件?
- r - 根据函数参数创建文件名,并根据函数中的条件创建文件名 - R
- mysql - 使 groupby 查询更快
- node.js - Node中的Mongo客户端没有收到连接响应
- angular - 移动友好的基于卡片的 Angular 组件替换可过滤和可排序表