简体   繁体   中英

How use Dependency Injection with Unity from Migration Code First?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM