jeudi 13 septembre 2018

Create instance and resolve dependencies

I have c# library that referenced in main project. The library

  1. Gets main project assembly;
  2. Retrieves all types using System.Reflection;
  3. Should creates type using Activator.CreateInstance (I’m not sure this is the best way).

The library doesn’t know anything about main project, only a metadata that can be obtained through reflection. How the dependencies can be resolved?

private readonly Assembly _assembly;

public Injector()
{
    _assembly = Assembly.GetEntryAssembly();
}

public List<string> GetTypes()
{
    return _assembly
        .GetTypes()
        .Select(x => x.FullName)
        .ToList();
}

public object GetType(string typeName)
{
    Type type = _assembly
        .GetTypes()
        .First(x => x.FullName == "web.Services.HistoryService");

    object instance = Activator.CreateInstance(type);

    return instance;
}

Possible issue: different IoC containers (third-party libraries, own-written).

What is the best way to handle this problem and keep library more automatic without forcing users provide a lot of settings? If it's not possible, could you please offer any other solutions? Thanks.





Aucun commentaire:

Enregistrer un commentaire