简体   繁体   中英

Can I use Spring.NET to inject dependencies in a created instance?

Is it possible to to something like this using Spring.NET IoC container?

MyClass instance = new MyClass();
ContextRegistry.GetContext().InjectDepenencies(instance);
// instance has the defined dependencies set

This would come in handy. Of couse I could use ContextRegistry.GetContext().Get("name") but that would create a new instance of the defined object. I would need to set the dependencies of an already created object.

There are three options available, the first one matches what you want.

  • IApplicationContext.ConfigureObject(object target, string name)

    This configures the target object using the object definition which is matched by the name argument.

  • IApplicationContext.Get(string name, object[] arguments)

    Which will either use the constructor or a static factory method which will receive the arguments as specified.

  • GenericApplicationContext.RegisterObjectDefinition(string name, IObjectDefinition definition)

    You can use it to register dependencies at runtime.

如果将name定义为singleton(这是spring.net中的默认范围ContextRegistry.GetContext().Get("name")ContextRegistry.GetContext().Get("name")将不会创建新实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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