代码之家  ›  专栏  ›  技术社区  ›  AwkwardCoder

未调用StructureMap InstanceInterceptor

  •  1
  • AwkwardCoder  · 技术社区  · 15 年前

    我想截获在SM中创建实例的过程,我正在尝试以下操作,但它没有调用InstanceInterceptor实现,有人知道为什么吗?

    ForRequestedType<IPublishResources>()
     .TheDefault
     .Is
     .OfConcreteType<PublisherService>()
     .InterceptWith(new PublisherServiceInterceptor());
    

    测试代码使用ObjectFactory创建实例,如下所示:

    // Given we have a configure object factory in StructureMap...
    ObjectFactory.Configure(x => x.AddRegistry(new StructureMapServiceRegistry()));
    
    // When we request a publisher service...
    var publisher = ObjectFactory.GetInstance<IPublishResources>();
    

    干杯

    AWC

    1 回复  |  直到 14 年前
        1
  •  2
  •   KevM    15 年前

    我无法在2.5.4版中重现您的问题。这是我的密码。

    public interface IPublishResources {}
    class PublishResources : IPublishResources {}
    public class LoggingInterceptor : InstanceInterceptor
    {
        //this interceptor is a silly example of one
        public object Process(object target, IContext context)
        {
            Console.WriteLine("Interceptor Called");
            return context.GetInstance<PublishResources>();
        }
    }
    
    public class MyRegistry : Registry
    {
        public MyRegistry()
        {
            For<IPublishResources>()
                .Use<PublishResources>()
                .InterceptWith(new LoggingInterceptor());
        }
    }
    
    [TestFixture]
    public class Structuremap_interception_configuraiton
    {
        [Test]
        public void connecting_implementations()
        {
            var container = new Container(cfg =>
            {
                cfg.AddRegistry<MyRegistry>();
            });
    
            container.GetInstance<IPublishResources>();
        }
    }
    

    一个问题。你真的需要在这里使用拦截器吗?如果你只需要定义一个工厂,你可以这样做。

        public interface IPublishResourcesFactory
    {
        IPublishResources Create();
    }
    
    public class MyRegistry : Registry
    {
        public MyRegistry()
        {
            For<IPublishResources>().Use(c =>
            {
                return c.GetInstance<IPublishResourcesFactory>().Create();
            });
    
            //or
    
            For<IPublishResources>().Use(c =>
            {
                //other object building code.
                return new PublishResources();
            });
        }
    }