Используйте единство инструмента внедрения зависимостей для создания объекта EF ObjectContext

Я попытался зарегистрировать тип в контейнере, используя приведенный ниже скрипт, он работает хорошо

 Container.RegisterType<System.Data.Objects.ObjectContext,
              ExSS.Repository.MyEntity>( "myentity", new InjectionConstructor());

однако, когда я пытаюсь использовать конфигурацию xml:

<alias alias="ObjectContext" 
        type="System.Data.Objects.ObjectContext,System.Data.Entity" />
<alias alias="MyEntity" type="ExSS.Repository.MyEntity,ExSS.Repository"/>
<register type="ExSS.Repository.MyEntity,ExSS.Repository" mapTo="MyEntity" 
        name="myentity">
    <constructor></constructor>
</register>

Это не работает. Сообщение об ошибке:

The type name or alias ObjectContext could not be resolved. Please check your 
configuration file and verify this type name. 

Описание:

An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error 
and where it originated in the code. 

Детали исключения:

System.InvalidOperationException: The type name or alias ObjectContext could 
not be resolved. Please check your configuration file and verify this type name.

Трассировка стека:

[InvalidOperationException: The type name or alias ObjectContext could not be resolved. Please check your configuration file and verify this type name.]
   Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveType(String typeNameOrAlias, Boolean throwIfResolveFails) +200
   Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolver.ResolveType(String typeNameOrAlias) +59
   Microsoft.Practices.Unity.Configuration.RegisterElement.GetRegisteringType() +70
   Microsoft.Practices.Unity.Configuration.RegisterElement.ConfigureContainer(IUnityContainer container) +111
   Microsoft.Practices.Unity.Configuration.ContainerConfiguringElement.ConfigureContainerInternal(IUnityContainer container) +39
   Microsoft.Practices.Unity.Configuration.<>c__DisplayClass1.<ConfigureContainer>b__0(ContainerConfiguringElement element) +42
   Microsoft.Practices.ObjectBuilder2.EnumerableExtensions.ForEach(IEnumerable`1 sequence, Action`1 action) +200
   Microsoft.Practices.Unity.Configuration.ContainerElement.ConfigureContainer(IUnityContainer container) +269
   Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.Configure(IUnityContainer container, String configuredContainerName) +133
   Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer container, UnityConfigurationSection section, String containerName) +70

может ли кто-нибудь дать несколько предложений? большое спасибо


person eason    schedule 16.03.2011    source источник


Ответы (2)


Нашел причину, она связана с тем, что сборка System.Data.Entity не могла корректно загружаться CLR. publicktokenkey и культура и версия должны быть добавлены. Конфиг ниже работает:

<alias alias="ObjectContext" type="System.Data.Objects.ObjectContext, System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> 
<alias alias="MyEntity" type="ExSS.Repository.MyEntity, ExSS.Repository"/> 
<register type="ObjectContext" mapTo="MyEntity" name="myentity"> 
  <constructor /> 
</register>
person eason    schedule 17.03.2011

Ваша конфигурация неверна. Так должно быть:

<alias alias="ObjectContext" type="System.Data.Objects.ObjectContext, System.Data.Entity" />
<alias alias="MyEntity" type="ExSS.Repository.MyEntity, ExSS.Repository"/>
<register type="ObjectContext" mapTo="MyEntity" name="myentity">
    <constructor />
</register>
person Ladislav Mrnka    schedule 16.03.2011
comment
Спасибо за ответ. Я изменил конфигурацию, как указано выше, получил то же сообщение об ошибке, что и раньше. кажется, объект не может быть зарегистрирован из xml, я сначала регистрирую его в коде - person eason; 17.03.2011
comment
: _container.RegisterType‹System.Data.Objects.ObjectContext, ExSS.Repository.MyEntity›(myentity,new InjectionConstructor()); и настроить другие классы в xml, некоторые из этих классов имеют поле, которое зависит от System.Data.Objects.ObjectContext, в xml это выглядит так: ‹имя контейнера=ExssUnityCfg› ‹register type=IRepositoryFactory mapTo=RepositoryFactory› ‹constructor› ‹param name =context type=ObjectContext› ‹имя зависимости=myentity type=ObjectContext /› ‹/param› ‹/constructor› ‹/container› - person eason; 17.03.2011
comment
но, к сожалению, я получил то же сообщение об ошибке. кажется, что контейнер ExssUnityCfg не может разрешить ObjectContext, определенный в коде - person eason; 17.03.2011