0

I need to use dependency injection in the Migrations\Configuration.cs for seeding values from my service layer. I use Unity to do that. My Unity container work fine in the entire web site because I instantiate all Interfaces via Constructor class. But I cannot do that in the Configuration.cs file because Code First use an empty Constructor.

Here is my code. Tell me what I’m doing wrong?

internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        private IGenderService _genderService;

        public Configuration()
        {
            AutomaticMigrationsEnabled = false;

            using (var container = UnityConfig.GetConfiguredContainer())
            {
                var isRegister = container.IsRegistered<IGenderService>(); // Return true!
                _genderService = container.Resolve<IGenderService>();

                if (_genderService == null)
                    throw new Exception("Doh! Empty");
                else
                    throw new Exception("Yeah! Can continue!!");
            };
        }

        public Configuration(IGenderService genderService) // Cannot use this constructor because of Code First!!!
        {
            _genderService = genderService;
        }
}

The _genderService is always null and I got this error in the same way :

Type 'Microsoft.Practices.Unity.ResolutionFailedException' in assembly 'Microsoft.Practices.Unity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

Thank,

David

David Létourneau
  • 1,250
  • 2
  • 19
  • 39

1 Answers1

0

I don't know Unity, but your question is a common DI patterns.

IMHO the problem is you pass your ioc container around, in Configuration ctor:

public Configuration()  {
  AutomaticMigrationsEnabled = false;
  using (var container = UnityConfig.GetConfiguredContainer())  {
        ....
  }

you should use a CompositionRoot:

public class Bootstrap {
  public void Register() {
     var container = new UnityContainer();
     container.RegisterType<IGenderService, GenderService>();
     container.RegisterType<Configuration>();

  }
}

internal sealed class Configuration:  {
  private IGenderService _genderService;
  public Configuration(IGenderService genderService) {
     _genderService = genderService;
  }
}

...
// resolving
var config = container.Resolve<Configuration>();

Behind the scenes, the Unity container first constructs a GenderService object and then passes it to the constructor of the Configuration class.

Community
  • 1
  • 1
o3o
  • 1,094
  • 13
  • 23