Intercept Ninject instance activation?

这一生的挚爱 提交于 2019-12-23 17:37:17

问题


I'm trying to put an example together of using Caliburn Micro on WP7 with Ninject. Everything was pretty straight forward. However, I'm stuck on how to go about firing an event once an instance is Activated by Ninject.

Here is the ActivateInstance method in Caliburn Micro's SimpleContainer, the IoC container that comes with CM for the phone.

 protected virtual object ActivateInstance(Type type, object[] args) {
            var instance = args.Length > 0 ? Activator.CreateInstance(type, args) : Activator.CreateInstance(type);
            Activated(instance);
            return instance;
        }

I register my types in Ninject and when they're activated I need to fire the Activated event. I looked at interception which might be the route to go but I don't think dynamic proxy and Linfu is going to work on the phone.

To clarify more, I'm not using the SimpleContainer, the above is to show what SimpleContainer does when an instance is activated. I have a NinjectBootstrapper and a NinjectContainer that implements IPhoneContainer. I can't figure out how to implement event Action<object> Activated; with Ninject.

update: .OnActivation() looks like the ticket.

Kernel.Bind<IMyService>().To<MyService>().InSingletonScope().OnActivation();

回答1:


You are on the wrong road. You shouldn't extend the SimpleContainer and use Ninject to activate the instances. This would mean you are using an IoC container to get the instances for an other IoC container.

Instead you have to change the Bootstrapper to use Ninject as your IoC container. There are plenty of examples on the web e.g. http://caliburnmicro.codeplex.com/discussions/230861

To use the Phone specific functions from IPhoneContainer you most likely sill have to put a wrapper around Ninject and implement the methods provided by this interface.


Update

You can add an IActivationStrategy as shown in th code below. But make sure you add it as the last strategy in case you have other ones.

this.Kernel.Components.Add<IActivationStrategy, ActivationNotificationActivationStrategy>();
this.Kernel.Components.GetAll<IActivationStrategy>()
    .OfType<ActivationNotificationActivationStrategy>()
    .Single().Activated += ...

public class ActivationNotificationActivationStrategy : NinjectComponent, IActivationStrategy
{
    public event Action<object> Activated;

    public void Activate(IContext context, InstanceReference reference)
    {
        if (this.Activated != null)
        {
            this.Activated(reference.Instance);
        }
    }

    public void Deactivate(IContext context, InstanceReference reference)
    {
    }
}

Btw. It would be nice you make the final implemention available somehow so that others can take advantage of your work.



来源:https://stackoverflow.com/questions/8651735/intercept-ninject-instance-activation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!