servicestack with funq - autowiring by convention

你说的曾经没有我的故事 提交于 2019-12-03 14:09:59

For simple queries like this it's best to just contact the source, e.g. here is the source code for RegisterAutoWired:

public IRegistration<T> RegisterAutoWired<T>()
{
    var serviceFactory = GenerateAutoWireFn<T>();
    return this.Register(serviceFactory);
}

It generates an auto-wired factory over a Concrete implementation. An interface has no implementation, it needs to be a concrete class.

And the source code for RegisterAs:

public IRegistration<TAs> RegisterAs<T, TAs>() where T : TAs 
{
    return this.RegisterAutoWiredAs<T, TAs>();
}

Which is just a shorter alias you can use instead of RegisterAutoWiredAs.

Do you mean "how can I implement a solution to search through assemblies and automatically register classes in ServiceStack IOC based on a convention?"

If so, I might have a solution for you:

  1. Create an interface that your inject-able classes will implement.
  2. Have your inject-able classes implement that interface.
  3. In the boot-strapping code use reflection to search your assemblies and get a list of all of the classes that implement the inject-able interface.
  4. Use reflection to get the class name and interface based on your conventions.
  5. Call the ServiceStack IOC method RegisterAutoWiredType and pass in the class and interface to register them.

For example if our naming convention is ClassName IClassName:

private static void RegisterCustomTypes(Container container)
{
  //Get the Assembly Where the injectable classes are located.
  var assembly = Assembly.GetAssembly(typeof(IInjectable));

  //Get the injectable classes 
  var types =assembly.GetTypes()
    .Where(m => m.IsClass && m.GetInterface("IInjectable") != null);

  //loop through the injectable classes
  foreach (var theType in types)
  {
    //set up the naming convention
    var className = theType.Name;
    var interfaceName = string.Concat("I", className);
    //create the interface based on the naming convention
    var theInterface = theType.GetInterface(interfaceName);
    //register the type with the convention
    container.RegisterAutoWiredType(theType, theInterface);
  }
}

public interface IInjectable
{

}

//This class can be injected
public interface ITestManager : IInjectable
{
    void Execute(int id);
}

public class TestManager : ITestManager
{
    public void Execute(int id)
    {
        throw new System.NotImplementedException();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!