ASP.Net Web API and Unity: Injecting Configuration Information Into Repositories

Recently I cam upon a situation where I needed to inject two file paths, stored in a constants file, into a file system service that would be used to list two types of files stored on the web server's file system. I was struggling with how to do this using the IoC pattern with Unity. I found a pretty simple solution using InjectionProperty and nameof.

Here is the interface that describes the FileSystemService.

public interface IFileSystemService
{
        string MachineFilesPath { get; set; }
        string FirmwareFilesPath { get; set; }
        List<FirmwareFile> GetFirmwareFiles();
        FirmwareFile GetFirmwareFileByName(string fileName);
        List<MachineFile> GetAllMachineFiles();
        List<MachineFile> GetMachineFiles(IEnumerable<RawMachineFile> files);
}

Here is the relevant code for the FileSystemService.

public class FileSystemService: IFileSystemService
{
        [Dependency]
        public string MachineFilesPath { get; set; }
        [Dependency]
        public string FirmwareFilesPath { get; set; }
        [Dependency]
        public IFileHasher _fileHasher { get; set; }
        //More code here...
    
}

Inside the BootStrapper or the UnityConfig, wherever you register your types, simply add InjectonProperties to the type registration. I was even able to use nameof on the IFileSystemService interface to pass the property name to Unity.

container.RegisterType<IFileHasher, FileHasher>();
container.RegisterType<IFileSystemService, FileSystemService>(
    new InjectionProperty(nameof(IFileSystemService.MachineFilesPath),
                          Constants.MACHINE_FILES_PATH),
    new InjectionProperty(nameof(IFileSystemService.FirmwareFilesPath),
                          Constants.FIRMWATE_PATH));