1

We have a class (in fact many) that have a static initialization function that it needs to carry out on an object within the dependency injection container (using Unity).

public class MyClass
{
    public static void InitializeMappings(IMapper mapper)
    {
        // Do stuff to mapper
    }
}

I would like the InitializeMappings function to be called whenever a new IMapper instance is instantiated by the Unity container.

I need help to:

  • Call the InitializeMappings function from the container
  • Resolve the mapper parameter for the function call
  • Connect up the call to InitializeMappings to the lifetime of IMapper implementations

How would I go about implementing/defining this?

2
  • 1
    It's a static method. You can easily call it yourself once during app startup. Commented Apr 15, 2013 at 8:28
  • @Steven - But then how do I bind the static function to the lifetime of the container item (that is, the IMapper)? Commented Apr 15, 2013 at 23:02

2 Answers 2

5

This is bad design; why not have the mapper implementations call the setup function in their constructors directly?

You can get the container to do this, either through an extension, or by using an injection factory. Something like this:

container.RegisterType<IMapper>(
    new WhateverLifetimeYouWant(),
    new InjectionFactory(
        c => {
            var mapper = c.Resolve<IMapper>("RealMapper");
            MyClass.InitializeMappings(mapper);
            return mapper;
        }
)
.RegisterType<IMapper, ActualMapper>("RealMapper");

Then whenever you do container.Resolve<IMapper>() it'll run that little chunk of code.

This only works through the API, not through config files.

Sign up to request clarification or add additional context in comments.

1 Comment

My mapper implementation was a class I didn't have access to. However, in hindsight I should have wrapped it up and done as you suggest at the top - by calling them in the constructor. But this approach only holds in the case where the number of mapper implementations is controlled. The injection factory idea worked great though. Thanks!
2

In WPF I believe you can do the following

container.RegisterType<Mapper, Mapper>();
container.Register<IMapper>(
    new InjectionFactory(c => {
        var mapper = c.Resolve<Mapper>(); 
        MyClass.InitializeMappings(mapper);
        return mapper;
    })
);

As far as "Connect up the call to the lifetime of the IMapper" I don't get what you mean. Any objects created and only referenced by the mapper object would be garbage collected when the mapper object was.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.