ninjectninject.web.mvctelerik-open-access

Ninject invalid cast exception


public partial class CTMSEntitiesModel : OpenAccessContext, ICTMSEntitiesModelUnitOfWork
{
    public CTMSEntitiesModel(string connection)
:base(connection, backend, metadataSource)
{ }
    // there are more IQueryable requests here
}

public interface ICTMSEntitiesContext : ICTMSEntitiesModelUnitOfWork
{
    FetchStrategy FetchStrategy { get; set; }
}

public interface ICTMSEntitiesModelUnitOfWork : IUnitOfWork
{
    //all the IQueryable requests are here
}

I need to bind the ICTMSEntitiesContext to CTMSEntitiesModel. How would I go about doing that? What am I doing wrong when I do this? It is throwing an InvalidCastException.

kernel.Bind(typeof(CTMSDAL.ICTMSEntitiesContext)).To(typeof(CTMSDAL.CTMSEntitiesModel)).InRequestScope()
            .WithConstructorArgument("connection", System.Configuration.ConfigurationManager.ConnectionStrings["CTMS_MVCConnection"].ConnectionString);

I would appreciate all the help you can provide! Thanks, Safris


Solution

  • You have to implement the ICTMSEntitiesContext in the CTMSEntitiesModel class. Otherwise there is no way to cast an instance of the class to the target interface.

    Given that you are using OpenAccess and the fact that the context class may be automatically generated I would suggest to you add the interface implementation into a new partial class in different project file to avoid losing the custom code after the original file is regenerated:

    public partial class CTMSEntitiesModel : ICTMSEntitiesContext
    {
        // FetchStrategy property is already defined
    }