【问题标题】:Lazy Initialization in custom IDependencyResolver with Windsor Castle使用 Windsor Castle 在自定义 IDependencyResolver 中进行延迟初始化
【发布时间】:2017-09-10 14:18:28
【问题描述】:

我正在使用温莎城堡。我有一个 Business 类和一个 Interceptor 配置如下:

windsorContainer.Register(Component.For<IMyBusinessInterface>()
    .ImplementedBy<MyBusinessClass>()
    .Interceptors<MyInterceptorAttribute>()
    .LifestyleTransient());

IMyBusinessInterface 和 MyBusinessClass 在项目 Business 内。 MyInterceptorAttribute 在项目 Interceptors 内。 Business 项目引用了Interceptors 项目。

MyInterceptorAttribute 用作MyBusinessClass 方法的数据注释

[MyInterceptorAttribute]
public class MyBusinessClass 
{
    public IUnitOfWork uow { get; set; }
    public MyBusinessClass(IUnitOfWork uow)
    {
        uow = uow;
    }

    [MyInterceptorAttribute]
    public MyReturnValue MyBusinessMethod(MyArguments arguments)
    {
        //...
    }
}

我需要在 MyInterceptorAttribute 类中传递(或检索)在温莎城堡容器中实例化的 unit of work 的相同实例。

此时我通过了两个不同的实例。

我无法在 MyInterceptorAttribute 中检索工作单元的实例,因为要获取 invocation.InvocationTarget 我将创建一个循环引用。

public class MyInterceptorAttribute : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        IMyBusinessInterface obj = invocation.InvocationTarget as MyBusinessClass; //I cannot do this because of circular reference

        //obj.uow = ..

    }
}

所以我想在MyInterceptorAttribute 中添加工作单元的公共属性,并通过依赖注入获得业务类工作单元的相同实例......像这样:

public class MyInterceptorAttribute : IInterceptor
{
    public IUnitOfWork uow { get; set; }

    public void Intercept(IInvocation invocation)
    {
        //uow...            
    }
}

但在这一刻,我得到了两个不同的实例。是否有可能获得相同的实例来修改例如温莎种姓的配置...我想使用DependsOn 或DynamicParameters 或类似的东西?

谢谢

【问题讨论】:

    标签: c# arguments castle-windsor interceptor


    【解决方案1】:

    不要将拦截器实现为属性,它由 .Net 运行时实例化,因此不能用于 Windsor 的依赖注入,而是尝试使用标准的 [Interceptor(typeof(MyInterceptor))] 属性。

    然后,您可以在 Windsor 注册 MyInterceptorin Windsor,使用您希望的任何生活方式,并且工作单元或任何其他依赖项的依赖注入将按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多