Register abstract class and resolve derived class?

Jan 12, 2011 at 6:54 PM

Can Unity resolve a specific derived instance from a registered abstract class? For example, assume I have the follow classes:

public abstract class Settings
{
    public bool Enabled { get; set; }
}

public class UserSettings
{
    public int Foo { get; set; }
}

public class BlogSettings
{
    public string Bar { get; set; }
}

public class UserService
{
    public UserService(UserSettings userSettings) {}
}

public class BlogService
{
    public BlogService(BlogSettings blogSettings) {}
}


What I'd like to do is to use an InjectionFactory to create/retrieve the various settings instances. While I could register each derived setting type in the container, it would be much more useful if I could just specify that I want use an injection factory for all derived types of the base Settings class. Is this possible?

Jan 14, 2011 at 6:41 AM

No, Unity doesn't work this way. You could write a custom extension to sneak in a custom Type mapping policy to map a derived type back into the base type, but it's a fairly specialized use case (this is the first time I've seen anyone ask for it) so it's not in the core.

 

Feb 9, 2011 at 8:33 PM
Edited Feb 9, 2011 at 8:40 PM

I ended up just registering each derived settings type with an injection factory. The code is below:

 

container.RegisterType<BlogSettings>(new PerRequestLifetimeManager(), new InjectionFactory(c => c.Resolve<ISettingsManager<BlogSettings>>().GetSettings()));

 

This seems straightforward enough to me, but it does seem a bit repetitious to have to do for each type that derives from Settings.

Feb 9, 2011 at 9:40 PM
Edited Feb 9, 2011 at 11:48 PM

Removing post because the code I posted does not work properly. Sorry. The above post is the way I'm doing this now.