Register DbContext using Unity

Sep 9, 2013 at 9:16 PM
Hi,

I am having problems with unity 3.0 and DbContext from Entity Framework 5.0, bellow are the interface and the implementation and after the contents of unity.config:

Interface
public interface IContexto : IDisposable
    {
        IDbSet<Cliente> ClienteSet { get; set; }
        IDbSet<ClienteTelefone> ClienteTelefoneSet { get; set; }
        IDbSet<Telefone> TelefoneSet { get; set; }

        DbEntityEntry Entry(object entity);
        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

        int SaveChanges();
    }
Implementation:
public class Contexto : DbContext, IContexto
{
    static Contexto()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Contexto>());
    }

    public Contexto()
    {
        Debug.WriteLine("Contexto " + GetHashCode());
    }

    public IDbSet<Cliente> ClienteSet { get; set; }
    public IDbSet<ClienteTelefone> ClienteTelefoneSet { get; set; }
    public IDbSet<Telefone> TelefoneSet { get; set; }

    protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
    {
        dbModelBuilder.Configurations.Add(new ClienteConfiguracao());
        dbModelBuilder.Configurations.Add(new ClienteTelefoneConfiguracao());
        dbModelBuilder.Configurations.Add(new TelefoneConfiguracao());
    }
}
Unity configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    
    <!-- Acesso -->
    <alias alias="IContexto" type="Dados.Acesso.Contratos.IContexto, Dados.Acesso.Contratos" />
    <alias alias="Contexto" type="Dados.Acesso.Implementacoes.Contexto, Dados.Acesso.Implementacoes" />
    
    <!-- Repositórios -->
    <alias alias="IClienteRepositorio" type="Dados.Repositorios.Contratos.IClienteRepositorio, Dados.Repositorios.Contratos"/>
    <alias alias="IClienteTelefoneRepositorio" type="Dados.Repositorios.Contratos.IClienteTelefoneRepositorio, Dados.Repositorios.Contratos"/>
    <alias alias="ITelefoneRepositorio" type="Dados.Repositorios.Contratos.ITelefoneRepositorio, Dados.Repositorios.Contratos"/>
    <alias alias="ClienteRepositorio" type="Dados.Repositorios.Implementacoes.ClienteRepositorio, Dados.Repositorios.Implementacoes"/>
    <alias alias="ClienteTelefoneRepositorio" type="Dados.Repositorios.Implementacoes.ClienteTelefoneRepositorio, Dados.Repositorios.Implementacoes"/>
    <alias alias="TelefoneRepositorio" type="Dados.Repositorios.Implementacoes.TelefoneRepositorio, Dados.Repositorios.Implementacoes"/>

    <!-- Unidade -->
    <alias alias="ITrabalho" type="Dados.Unidade.Contratos.ITrabalho, Dados.Unidade.Contratos"/>
    <alias alias="Trabalho" type="Dados.Unidade.Implementacoes.Trabalho, Dados.Unidade.Implementacoes"/>

    <!-- Serviços -->
    <alias alias="IClienteServico" type="Servicos.Contratos.IClienteServico, Servicos.Contratos"/>
    <alias alias="ClienteServico" type="Servicos.Implementacoes.ClienteServico, Servicos.Implementacoes"/>

    <container>
        <register type="IContexto" mapTo="Contexto" >
            <lifetime type="perthread" />
        </register>
        <register type="IClienteRepositorio" mapTo="ClienteRepositorio" />
        <register type="IClienteTelefoneRepositorio" mapTo="ClienteTelefoneRepositorio" />
        <register type="ITelefoneRepositorio" mapTo="TelefoneRepositorio" />
        <register type="ITrabalho" mapTo="Trabalho" />
        <register type="IClienteServico" mapTo="ClienteServico" />
    </container>
    
</unity>
The current configuration is used in a WCF service and I have setup everything accoding to Unity Developer's Guide, I think the problem I am having has something to do with the fact that DbContext have a generic Entry method which unity does not know what to do with.

Bellow the error messages:

Server Error in '/Imobiliaria' Application.

Method not found: 'System.Data.Entity.Infrastructure.DbEntityEntry1<!!0> Dados.Acesso.Contratos.IContexto.Entry(!!0)'.

Description: 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.

Exception Details: System.MissingMethodException: Method not found: 'System.Data.Entity.Infrastructure.DbEntityEntry
1<!!0> Dados.Acesso.Contratos.IContexto.Entry(!!0)'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[MissingMethodException: Method not found: 'System.Data.Entity.Infrastructure.DbEntityEntry1<!!0> Dados.Acesso.Contratos.IContexto.Entry(!!0)'.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +153
System.Type.GetType(String typeName) +89
Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveAlias(String typeNameOrAlias) +229
Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveType(String typeNameOrAlias, Boolean throwIfResolveFails) +45
Microsoft.Practices.Unity.Configuration.RegisterElement.ConfigureContainer(IUnityContainer container) +130
Microsoft.Practices.Unity.Configuration.<>c__DisplayClass1.<ConfigureContainer>b__0(ContainerConfiguringElement element) +25
Microsoft.Practices.ObjectBuilder2.EnumerableExtensions.ForEach(IEnumerable
1 sequence, Action`1 action) +163
Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer container, UnityConfigurationSection section, String containerName) +220
Hospedagem.ServicosComunicacao.UnityServiceHostFactory.RegisterTypes(IUnityContainer container) in c:\Users\adriano\Documents\Visual Studio 2012\Projects\Imobiliaria\Hospedagem.ServicosComunicacao\UnityServiceHostFactory.cs:27
Hospedagem.ServicosComunicacao.UnityServiceHostFactory..ctor() in c:\Users\adriano\Documents\Visual Studio 2012\Projects\Imobiliaria\Hospedagem.ServicosComunicacao\UnityServiceHostFactory.cs:16

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +743
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1236
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +76
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +901

[ServiceActivationException: The service '/Imobiliaria/ClienteServicoComunicacao.svc' cannot be activated due to an exception during compilation. The exception message is: Exception has been thrown by the target of an invocation..]
System.Runtime.AsyncResult.End(IAsyncResult result) +650220
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +210733
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +282

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18045

Hope someone can help me.

Thanks in advance.

Carlos Adriano Portes
Editor
Sep 10, 2013 at 6:18 AM
The error occurs while trying to load the container configuration from the config file. You've posted some code and configuration which is good but there are a lot of moving pieces here. I wasn't able to find any issue with the IContexto/Contexto that you posted so I suspect the error may be occurring on the repositories (or someplace else not posted).

If you could post a complete example/sample that recreates the issue that would be a big help.

Also, you mention that you are using Unity 3 and .NET 4.0.30319 but Unity 3 requires .NET 4.5. Could you verify the versions you are using? Thanks.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Sep 10, 2013 at 3:24 PM
Edited Sep 10, 2013 at 3:45 PM
Randy,

Thank you for helping, I will send you an e-mail with a working copy and a not-working copy, the changes are only in IContexto interface, the database will automatically be created by code first, a sql server one.

Version information provided is the one provided by IIS, even though .NET 4.5 is installed and configured IIS shows 4.0, the same occurs with version 2.0 and its update 3.5.

Thanks in advance.

Carlos Adriano Portes