RegisterType with an interface in UnityContainer

限于喜欢 提交于 2019-12-04 11:15:38
er-v

Well this depends on the type of lifetime management you are using. Here:

  container.RegisterType<IImporter, Importer1>();

you use transient one, so you can do the following:

var container = new UnityContainer();

if (useFirstImport) {
    container.RegisterType<IImporter, Importer1>();
    container.RegisterType<IDeviceImporter, Importer1>();

} else {
    container.RegisterType<IImporter, Importer2>();
    container.RegisterType<IDeviceImporter, Importer2>();
}

without fear of bugs. container.Resolve<IImporter>() will create new instance on every call, just like container.Resolve<IDeviceImporter>() will.

But if you are using ContainerControlledLifetimeManager then anyway you'll have to use container.RegisterInstance<IDeviceImporter>(container.Resolve<IImporter>()) because Unity offers no other way to do this.

This feature is really interesting, it would be very nice to have something like container.CreateSymLink<IDeviceImporter, IImporter>() but there is no such a thing.

I'm using ContainerControlledLifetimeManager, and end up with a code like:

var container = new UnityContainer();
System.Type importerType
if (useFirstImport) {
    importerType = GetType(Importer1);
} else {
    importerType = GetType(Importer2);
}

container.RegisterType(GetType(IImporter), importerType);
container.RegisterType(GetType(IDeviceImporter), importerType);
container.RegisterType(GetType(IFileImporter), importerType);

But yes, the best thing would be to have something like:

container.CreateSymLink<IDeviceImporter, IImporter>()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!