2
votes

Let's say I have the following classes.

public class Service1
{
   public Service1(Dependency1 dependency1, Dependency2 dependency2, string myAppSetting)
   {
   }
}

public class Service2
{
   public Service2(DependencyA dependency1, ..., DependencyD dependency4, string myAppSetting)
   {
   }
}

Unity container is used to populate the constructor parameters through dependency injection; container.Resolve(..) methods are never called directly.

The above classes have various parameters but the last parameter string myAppSetting is always the same. Is there a way to configure the Unity container to always resolve a parameter with a specific primitive type and name to a specific value in different classes?

I know that you can register injection constructors for every type which seems brittle to me. The other way might be wrapping the string parameter in a custom class. But I was wondering if there is a way to do with specific primitive type constructor parameters.

2

2 Answers

2
votes

I have made a interface to wrap my AppSettings. This allows me to inject application settings into my types.

IAppSettings

public interface IAppSettings {
    string MySetting { get; set; }
    ...
}

UnityConfig

container.RegisterInstance<IAppSettings>(AppSettings.Current);
container.RegisterType<IService1, Service1>();
container.RegisterType<IService2, Service2>();

Service1

public class Service1
{
    public Service1(Dependency1 dependency1, Dependency2 dependency2, IAppSettings appSettings)
    {
        var mySetting = appSettings.MySetting;
    }
}

Here are some options for your primitive parameters: Register a type with primitive-arguments constructor?

0
votes

I don't think you can get Unity to resolve all string parameters named "myAppSettings" for any class. But, you can get it to resolve parameters by name for particular classes. Something like:

Container.RegisterType<Service2, Service2>(
            new InjectionConstructor(
                    new ResolvedParameter<string>(), 
                        "myAppSetting"));