2010-01-26 11 views
1

我想拦截在SM中创建一个实例,我正在尝试以下,但它不调用InstanceInterceptor实现,有谁知道为什么吗?StructureMap 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

回答

2

我不能在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>(); 
    } 
} 

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

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(); 
     }); 
    } 
} 
+0

Ia格力与你我实际上并不需要它,并已经改变了代码 - 谢谢你的信息,但... – AwkwardCoder 2010-02-01 16:01:17