ory*_*yol 6 c# dependency-injection autofac
例如,我在类型的构造函数中使用一个参数注册了类C1 System.Type.我有另一个类(C2),注入参数类型为C1.我希望typeof(C2)在C1构造函数中自动接收.有可能吗?
示例代码:
public class C1
{
public C1(Type type) {}
// ...
}
public class C2
{
public C2(C1 c1) {}
// ...
}
// Registration
containerBuilder.Register(???);
containerBuilder.Register<C2>();
Run Code Online (Sandbox Code Playgroud)
这应该这样做:
builder.RegisterType<C1>();
builder.RegisterType<C2>();
builder.RegisterModule(new ExposeRequestorTypeModule());
Run Code Online (Sandbox Code Playgroud)
哪里:
class ExposeRequestorTypeModule : Autofac.Module
{
Parameter _exposeRequestorTypeParameter = new ResolvedParameter(
(pi, c) => c.IsRegistered(pi.ParameterType),
(pi, c) => c.Resolve(
pi.ParameterType,
TypedParameter.From(pi.Member.DeclaringType)));
protected override void AttachToComponentRegistration(
IComponentRegistry registry,
IComponentRegistration registration)
{
registration.Preparing += (s, e) => {
e.Parameters = new[] { _exposeRequestorTypeParameter }
.Concat(e.Parameters);
};
}
}
Run Code Online (Sandbox Code Playgroud)
任何带System.Type参数的组件都将获得传递给它的请求者的类型(如果有的话).可能的改进可能是使用a NamedParameter而不是TypedParameter限制Type仅与具有特定名称的参数匹配的参数.
如果这有效,请告诉我,其他人已经询问了相同的一般任务,这将很好地与他们分享.
| 归档时间: |
|
| 查看次数: |
999 次 |
| 最近记录: |