C# 使用windsor安装时解决的类型访问问题

C# 使用windsor安装时解决的类型访问问题,c#,castle-windsor,C#,Castle Windsor,我有大量依赖于看门狗组件的类。我向watchdog实例添加了对dependent类的引用 目前,我使用以下代码来实现这一点 class MyClass { public MyClass(IWatchDog watchDog) { watchDog.WatchingType = typeof(MyClass); } } 我的安装程序: class IoC: IWindsorInstaller { public void Install(

我有大量依赖于看门狗组件的类。我向watchdog实例添加了对dependent类的引用

目前,我使用以下代码来实现这一点

   class MyClass {
      public MyClass(IWatchDog watchDog) {
        watchDog.WatchingType = typeof(MyClass);
      }
   }
我的安装程序:

class IoC: IWindsorInstaller {
    public void Install(IWindsorContainer container, IConfigurationStore store) {
        container.Register(Component.For<MyClass>());
        container.Register(Component.For<IWatchDog>().ImplementedBy<WatchDogService>());
    }
}
class-IoC:IWindsorInstaller{
public void安装(IWindsorContainer、IConfigurationStore){
container.Register(Component.For());
container.Register(Component.For().ImplementedBy());
}
}
是否可以让安装人员为我执行此任务?以下是我在伪代码中的想法,解析是我想象的方法:

class IoC : IWindsorInstaller {
    public void Install(IWindsorContainer container, IConfigurationStore store) {
        container.Register(Component.For<MyClass>());
        container.Register(
            Component.For<IWatchDog>()
                .ImplementedBy<WatchDogService>()
                .OnResolving<IWatchDog>(
                    new Action((Type typeBeingResolved, IWatchDog instance) =>
                        instance.WatchingType = typeBeingResolved));

    }
}
class-IoC:IWindsorInstaller{
public void安装(IWindsorContainer、IConfigurationStore){
container.Register(Component.For());
集装箱。登记(
用于()的组件
.由()实施
.OnResolving(
新操作((键入typeBeingResolved,IWatchDog实例)=>
instance.WatchingType=typeBeingResolved));
}
}
因此,在本例中,我想象
typeBeingResolved
将等于
typeof(MyClass)
如果调用
container.Resolve()
,或者
null
如果有人调用
container.Resolve()


显然,如果我能够以某种方式访问正在解析的类型的实例,就像在
OnCreate()
中一样,这也会起作用。

使用自定义工具,您可以将组件的默认激活器更改为您想要的激活器。下面是一个可行的解决方案:

using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace ComponentCreater
{
public interface IWatchDogService
{
    Type WatchingType { get; set; }
}

public class WatchDogService : IWatchDogService
{
    public Type WatchingType { get; set; }
}


public class WatchedClassViaConstructor
{
    private readonly IWatchDogService watchDogService;

    public WatchedClassViaConstructor(IWatchDogService watchDogService)
    {
        this.watchDogService = watchDogService;
    }

    public void Print()
    {
        Console.WriteLine(this.watchDogService.WatchingType.Name);
    }
}

public class WatchDogFacility : AbstractFacility
{
    protected override void Init()
    {
        this.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
    }

    private void Kernel_ComponentModelCreated(ComponentModel model)
    {
        model.CustomComponentActivator = typeof(WatchedComponentActivator);   
    }
}

public class WatchedComponentActivator : DefaultComponentActivator
{
    public WatchedComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {
    }

    protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
    {
        object component = base.CreateInstance(context, constructor, arguments);

        if (arguments != null)
        {
            IWatchDogService watchDogService = arguments.FirstOrDefault(arg => arg is IWatchDogService) as IWatchDogService;
            if (watchDogService != null)
            {
                watchDogService.WatchingType = component.GetType();
            }
        }

        return component;
    }
}

class Program
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();
        container.AddFacility<WatchDogFacility>();

        container.Register(
            Component.For<IWatchDogService>()
                .ImplementedBy<WatchDogService>()
                .LifestyleTransient(),
            Component.For<WatchedClassViaConstructor>()
        );

        WatchedClassViaConstructor obj = container.Resolve<WatchedClassViaConstructor>();
        obj.Print();
        Console.ReadLine();
    }
}
这使用了相同的策略,但使用了属性注入。我创建了一个组件模型构造贡献者,以强制castle要求注入IWatchDogServcie,就像是构造函数注入一样。下面是代码:

namespace ComponentCreater2
{
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.ModelBuilder;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public interface IWatchDogService
{
    Type WatchingType { get; set; }
}

public class WatchDogService : IWatchDogService
{
    public Type WatchingType { get; set; }
}

public interface IIsWatched
{
    IWatchDogService WatchDogService { get; set; }
}

public abstract class WatchedClass : IIsWatched
{
    public IWatchDogService WatchDogService { get; set; }
}

public class WatchedClassViaInheritance : WatchedClass
{
    public void Print()
    {
        Console.WriteLine(this.WatchDogService.WatchingType.Name);
    }
}

public class WatchDogFacility : AbstractFacility
{
    protected override void Init()
    {
        this.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
        this.Kernel.ComponentModelBuilder.AddContributor(new RequireWatchDogService());
    }

    private void Kernel_ComponentModelCreated(ComponentModel model)
    {
        if (typeof(IIsWatched).IsAssignableFrom(model.Implementation))
        {
            model.CustomComponentActivator = typeof(WatchedComponentActivator);
        }
    }
}

public class WatchedComponentActivator : DefaultComponentActivator
{
    public WatchedComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {
    }
    protected override void SetUpProperties(object instance, CreationContext context)
    {
        base.SetUpProperties(instance, context);

        IIsWatched watched = instance as IIsWatched;

        if (watched != null)
        {
            watched.WatchDogService.WatchingType = instance.GetType();
        }
    }
}

public class RequireWatchDogService : IContributeComponentModelConstruction
{
   public void ProcessModel(IKernel kernel, ComponentModel model) 
   { 
       model.Properties.Where(prop => prop.Dependency.TargetType == typeof(IWatchDogService))
           .All(prop => prop.Dependency.IsOptional = false); 
   } 
}


class Program2
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();
        container.AddFacility<WatchDogFacility>();

        container.Register(
            Component.For<IWatchDogService>()
                .ImplementedBy<WatchDogService>()
                .LifestyleTransient(),
            Component.For<WatchedClassViaInheritance>()
        );

        WatchedClassViaInheritance obj = container.Resolve<WatchedClassViaInheritance>();
        obj.Print();
        Console.ReadLine();
    }
}
名称空间组件creater2
{
使用Castle.Core;
使用Castle.MicroKernel;
使用Castle.MicroKernel.ComponentActivator;
使用Castle.MicroKernel.Context;
使用Castle.MicroKernel.Facilities;
使用Castle.MicroKernel.ModelBuilder;
使用Castle.MicroKernel.Registration;
使用温莎城堡;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
公共接口IWatchDogService
{
类型监视类型{get;set;}
}
公共类WatchDogService:IWatchDogService
{
公共类型监视类型{get;set;}
}
公共接口IIsWatched
{
IWatchDogService WatchDogService{get;set;}
}
公共抽象类WatchedClass:IIsWatched
{
公共IWatchDogService WatchDogService{get;set;}
}
公共类WatchedClassVia继承:WatchedClass
{
公开作废印刷品()
{
WriteLine(this.WatchDogService.WatchingType.Name);
}
}
公共类看门狗设施:AbstractFacility
{
受保护的重写void Init()
{
this.Kernel.ComponentModelCreated+=Kernel\u ComponentModelCreated;
this.Kernel.ComponentModelBuilder.AddContributor(新的RequireWatchDogService());
}
私有void内核\u ComponentModel已创建(ComponentModel模型)
{
if(typeof(IIsWatched).IsAssignableFrom(model.Implementation))
{
model.CustomComponentActivator=类型(WatchedComponentActivator);
}
}
}
公共类WatchedComponentActivator:DefaultComponentActivator
{
公共监视ComponentActivator(ComponentModel模型、IKernel内核、ComponentInstanceDelegate onCreation、ComponentInstanceDelegate onDestruction)
:base(模型、内核、onCreation、onDestruction)
{
}
受保护的覆盖无效设置属性(对象实例、CreationContext上下文)
{
SetUpProperties(实例、上下文);
IIsWatched watched=实例为IIsWatched;
如果(监视!=null)
{
watch.WatchDogService.WatchingType=instance.GetType();
}
}
}
公共类RequireWatchDogService:IContributeComponentModelConstruction
{
公共void进程模型(IKernel内核、组件模型)
{ 
model.Properties.Where(prop=>prop.Dependency.TargetType==typeof(IWatchDogService))
.All(prop=>prop.Dependency.IsOptional=false);
} 
}
班级计划2
{
静态void Main(字符串[]参数)
{
IWindsorContainer=新WindsorContainer();
container.AddFacility();
集装箱。登记(
用于()的组件
.由()实施
.生活方式,
用于()的组件
);
watchedClassViaInheritation obj=container.Resolve();
obj.Print();
Console.ReadLine();
}
}

}

使用自定义工具,您可以将组件的默认激活器更改为您想要的激活器。下面是一个可行的解决方案:

using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace ComponentCreater
{
public interface IWatchDogService
{
    Type WatchingType { get; set; }
}

public class WatchDogService : IWatchDogService
{
    public Type WatchingType { get; set; }
}


public class WatchedClassViaConstructor
{
    private readonly IWatchDogService watchDogService;

    public WatchedClassViaConstructor(IWatchDogService watchDogService)
    {
        this.watchDogService = watchDogService;
    }

    public void Print()
    {
        Console.WriteLine(this.watchDogService.WatchingType.Name);
    }
}

public class WatchDogFacility : AbstractFacility
{
    protected override void Init()
    {
        this.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
    }

    private void Kernel_ComponentModelCreated(ComponentModel model)
    {
        model.CustomComponentActivator = typeof(WatchedComponentActivator);   
    }
}

public class WatchedComponentActivator : DefaultComponentActivator
{
    public WatchedComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {
    }

    protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
    {
        object component = base.CreateInstance(context, constructor, arguments);

        if (arguments != null)
        {
            IWatchDogService watchDogService = arguments.FirstOrDefault(arg => arg is IWatchDogService) as IWatchDogService;
            if (watchDogService != null)
            {
                watchDogService.WatchingType = component.GetType();
            }
        }

        return component;
    }
}

class Program
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();
        container.AddFacility<WatchDogFacility>();

        container.Register(
            Component.For<IWatchDogService>()
                .ImplementedBy<WatchDogService>()
                .LifestyleTransient(),
            Component.For<WatchedClassViaConstructor>()
        );

        WatchedClassViaConstructor obj = container.Resolve<WatchedClassViaConstructor>();
        obj.Print();
        Console.ReadLine();
    }
}
这使用了相同的策略,但使用了属性注入。我创建了一个组件模型构造贡献者,以强制castle要求注入IWatchDogServcie,就像是构造函数注入一样。下面是代码:

namespace ComponentCreater2
{
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.ModelBuilder;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public interface IWatchDogService
{
    Type WatchingType { get; set; }
}

public class WatchDogService : IWatchDogService
{
    public Type WatchingType { get; set; }
}

public interface IIsWatched
{
    IWatchDogService WatchDogService { get; set; }
}

public abstract class WatchedClass : IIsWatched
{
    public IWatchDogService WatchDogService { get; set; }
}

public class WatchedClassViaInheritance : WatchedClass
{
    public void Print()
    {
        Console.WriteLine(this.WatchDogService.WatchingType.Name);
    }
}

public class WatchDogFacility : AbstractFacility
{
    protected override void Init()
    {
        this.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
        this.Kernel.ComponentModelBuilder.AddContributor(new RequireWatchDogService());
    }

    private void Kernel_ComponentModelCreated(ComponentModel model)
    {
        if (typeof(IIsWatched).IsAssignableFrom(model.Implementation))
        {
            model.CustomComponentActivator = typeof(WatchedComponentActivator);
        }
    }
}

public class WatchedComponentActivator : DefaultComponentActivator
{
    public WatchedComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {
    }
    protected override void SetUpProperties(object instance, CreationContext context)
    {
        base.SetUpProperties(instance, context);

        IIsWatched watched = instance as IIsWatched;

        if (watched != null)
        {
            watched.WatchDogService.WatchingType = instance.GetType();
        }
    }
}

public class RequireWatchDogService : IContributeComponentModelConstruction
{
   public void ProcessModel(IKernel kernel, ComponentModel model) 
   { 
       model.Properties.Where(prop => prop.Dependency.TargetType == typeof(IWatchDogService))
           .All(prop => prop.Dependency.IsOptional = false); 
   } 
}


class Program2
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();
        container.AddFacility<WatchDogFacility>();

        container.Register(
            Component.For<IWatchDogService>()
                .ImplementedBy<WatchDogService>()
                .LifestyleTransient(),
            Component.For<WatchedClassViaInheritance>()
        );

        WatchedClassViaInheritance obj = container.Resolve<WatchedClassViaInheritance>();
        obj.Print();
        Console.ReadLine();
    }
}
名称空间组件creater2
{
使用Castle.Core;
使用Castle.MicroKernel;
使用Castle.MicroKernel.ComponentActivator;
使用Castle.MicroKernel.Context;
使用Castle.MicroKernel.Facilities;
使用Castle.MicroKernel.ModelBuilder;
使用Castle.MicroKernel.Registration;
使用温莎城堡;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
公共接口IWatchDogService
{
类型监视类型{get;set;}
}
公共类WatchDogService:IWatchDogService
{
公共类型监视类型{get;set;}
}
公共接口IIsWatched
{
IWatchDogService WatchDogService{get;set;}
}
公共抽象类WatchedClass:IIsWatched
{
公共IWatchDogService WatchDogService{get;set;}
}
公共信用