/// <summary> /// 如果某个类型未在容器注册,则注册该类型 /// </summary> /// <param name="container"></param> /// <param name="alias"></param> /// <param name="registerType"></param> /// <param name="registerAsSingleton"></param> /// <param name="autoWiringMode"></param> public static void RegisterTypeIfMissing(this IApplicationContext container, string alias, Type registerType, bool registerAsSingleton, AutoWiringMode autoWiringMode, bool lazyInit = false) { Type typeToRegister = registerType; if (!container.ContainsObjectDefinition(alias)) { DefaultObjectDefinitionFactory definitionFactory = new DefaultObjectDefinitionFactory(); ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.RootObjectDefinition(definitionFactory, typeToRegister); builder.SetSingleton(registerAsSingleton); builder.SetAutowireMode(autoWiringMode); builder.SetLazyInit(lazyInit); IConfigurableApplicationContext configurableContext = container as IConfigurableApplicationContext; IObjectDefinitionRegistry definitionRegistry = container as IObjectDefinitionRegistry; if (definitionRegistry != null) { definitionRegistry.RegisterObjectDefinition(alias, builder.ObjectDefinition); //if (configurableContext != null) //{ // configurableContext.Refresh(); //} } } }
private void RegisterTypeIfMissing(string alias, Type typeToRegister, bool registerAsSingleton) { if (!container.ContainsObjectDefinition(alias)) { DefaultObjectDefinitionFactory definitionFactory = new DefaultObjectDefinitionFactory(); ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.RootObjectDefinition(definitionFactory, typeToRegister); builder.SetSingleton(registerAsSingleton); builder.SetAutowireMode(AutoWiringMode.Constructor); IConfigurableApplicationContext configurableContext = container as IConfigurableApplicationContext; IObjectDefinitionRegistry definitionRegistry = container as IObjectDefinitionRegistry; if (definitionRegistry != null) { definitionRegistry.RegisterObjectDefinition(alias, builder.ObjectDefinition); //刷新后会导致之间加载的实例对象丢失 //if (configurableContext != null) //{ // configurableContext.Refresh(); //} } } }