ironcurtain
ironcurtain

Reputation: 690

Inject connection string to DbContext

I have external service which I can't modify, but I can only add new Class Libraries to it to extent it's functionality. My problem is that my class library uses EF->Repository->Service and IOC container and when I attach my library to external service it does not work as this service has no Connection String defined. I found that I can user Service Locator to define implement IOC container in my Class Library:

internal class ServiceLocator
{
    static ServiceLocator()
    {
        Current = new DefaultServiceLocator();
    }

    public static IServiceLocator Current { get; }

    private sealed class DefaultServiceLocator : IServiceLocator
    {
        private readonly IKernel _kernel;  // Ninject kernel

        public DefaultServiceLocator()
        {
            _kernel = new StandardKernel();
            LoadBindings();
        }

        public T Get<T>()
        {
            return _kernel.Get<T>();
        }

        private void LoadBindings()
        {

            string name = ""; // connection string
            _kernel.Bind<DbContext>().ToConstructor(_ => new Entities(name));
            _kernel.Bind<IRegionService>().To<RegionService>();
            _kernel.Bind<IRegionRepository>().To<RegionRepository>();
            _kernel.Bind<IMapper>().ToConstant(AutoMapperConfig.Initialize());
        }
    }
}

I created my own partial class to pass connection string to the constructor:

public partial class Entities
{
    public Entities(string name)
        :base(name)
    {
    }
}

as auto-generated class does not allow to pass connection string (and I don't want to modify this):

public partial class Entities : DbContext
{
   public Entities()
    : base("name=Entities")
   {
   }
}

When I run my test application in debug mode I see that it refers to auto-generated DbContext class instead to this created by me. As I said earlier I can't modify external service to just add connection string into App.config file. Kindly provide me any possible solutions to my problem. I am open to design changes.

Upvotes: 1

Views: 720

Answers (1)

Jan Muncinsky
Jan Muncinsky

Reputation: 4418

It seems, that some of your classes expect Entities dependency instead of DbContext. In this case Ninject tends to fallback to implicit self-binding and chooses constructor with dependencies that be can resolved (default in this case).

Try this binding instead:

_kernel.Bind<Entities>().ToConstructor(_ => new Entities(name));

Upvotes: 1

Related Questions