简体   繁体   English

如何在不使用泛型的情况下在ServiceStack中注册类型

[英]How to Register a Type in ServiceStack without using Generics

It is possible to register a type in ServiceStack Container using a object instance and its Type? 可以使用对象实例及其类型在ServiceStack Container中注册类型吗?

 object type_to_be_registered;
 Type type = type_to_be_registered.GetType();

The "type_to_be_registered" implements some interfaces and I want to register the "type_to_be_registered" for its interfaces. “type_to_be_registered”实现了一些接口,我想为其接口注册“type_to_be_registered”。 I can get the interfaces using the following code: 我可以使用以下代码获取接口:

Type[] interfaces = type.GetInterfaces();

But how can I register the object for each of its implemented interfaces, since I do not know (at compiling time) the type of the "type_to_be_registered" object and its interfaces?? 但是我如何为每个实现的接口注册对象,因为我不知道(在编译时)“type_to_be_registered”对象及其接口的类型?

Please read the docs for IOC in ServiceStack . 请阅读ServiceStack中的IOC文档 Here are some examples that registers using a runtime type: 以下是使用运行时类型注册的一些示例:

container.RegisterAutoWiredType(typeof(MyType));
container.RegisterAutoWiredType(typeof(MyType),typeof(IMyType));
container.RegisterAutoWiredTypes(typeof(MyType),typeof(MyType2),typeof(MyType3));

You can just register the instance as a Singleton with: 您可以将实例注册为Singleton:

container.Register(instance);

As well as use the CreateInstance() extension method to create an instance from a type: 除了使用CreateInstance()扩展方法从类型创建实例:

container.Register(type.CreateInstance());

If you want to register the instance of a different type, you can use reflection to call the generic method, eg: 如果要注册其他类型的实例,可以使用反射来调用泛型方法,例如:

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;
    }
}

Then you can register it with: 然后你可以注册:

container.Register(instance, type(AlternateType));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM