C# 如何在不使用泛型的情况下在ServiceStack中注册类型
可以使用对象实例及其类型在ServiceStack容器中注册类型C# 如何在不使用泛型的情况下在ServiceStack中注册类型,c#,asp.net,
servicestack,C#,Asp.net,
servicestack,可以使用对象实例及其类型在ServiceStack容器中注册类型 object type_to_be_registered; Type type = type_to_be_registered.GetType(); “type_to_be_registed”实现了一些接口,我想为其接口注册“type_to_be_registed”。我可以使用以下代码获取接口: Type[] interfaces = type.GetInterfaces(); 但是我如何为每个实现的接口注册对象,因为我不
object type_to_be_registered;
Type type = type_to_be_registered.GetType();
“type_to_be_registed”实现了一些接口,我想为其接口注册“type_to_be_registed”。我可以使用以下代码获取接口:
Type[] interfaces = type.GetInterfaces();
但是我如何为每个实现的接口注册对象,因为我不知道(在编译时)“type_to_be_注册”对象及其接口的类型???请阅读。以下是一些使用运行时类型注册的示例:
container.RegisterAutoWiredType(typeof(MyType));
container.RegisterAutoWiredType(typeof(MyType),typeof(IMyType));
container.RegisterAutoWiredTypes(typeof(MyType),typeof(MyType2),typeof(MyType3));
您只需将实例注册为Singleton即可:
container.Register(instance);
以及使用CreateInstance()
扩展方法从类型创建实例:
container.Register(type.CreateInstance());
如果要注册不同类型的实例,可以使用反射调用泛型方法,例如:
public static class ContainerExtensions
{
public static Container Register(this Container container,
object instance, Type asType)
{
var mi = container.GetType()
.GetMethods()
.First(x => x.Name == "Register"
&& x.GetParameters().Length == 1
&& x.ReturnType == typeof(void))
.MakeGenericMethod(asType);
mi.Invoke(container, new[] { instance });
return container;
}
}
然后,您可以在以下位置注册:
container.Register(instance, type(AlternateType));
你到底有什么问题?这似乎非常简单,您需要描述您的问题,除了您尚未将代码键入Visual Studio IDE之外…我不希望类型自动连接,我想注册一个实例。@nohros不清楚您到底想要什么,所以我又添加了几个示例。我想做的事情与上一个代码类似。我有一个对象,不知道它的实现接口(在编译时),但需要使用Type.GetInterfaces()返回的接口注册它。唯一的方法是为Container类创建一个扩展方法??如果我使用Container.Regsiter(实例)注册实例,它将被注册为一个对象,并且没有解析。@nohros我已经提供了您要求的解决方案,如果要为每个接口注册该方法,请在迭代类型接口时调用该方法。您不需要使用扩展方法,将impl复制到任何您想要的地方,但是扩展方法确实使调用站点看起来更直观。