views:

82

answers:

1

I want to intercept the creation of an instance in SM and I'm trying the following but it's not calling the InstanceInterceptor implementation, does anyone know why?

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

The test code uses the ObjectFactory to create instances, and is shown below:

// 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>();

Cheers

AWC

+1  A: 

I could not reproduce your problem in release 2.5.4. Here is my code.

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

A question. Do you really need to use an Interceptor here? If you only need to define a factory you can do somethign like this.

    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();
        });
    }
}
KevM
Ia gree with you I don't actually need it and changed the code already - thanks for the info though...
AWC