register dependency Unity

守給你的承諾、 提交于 2019-12-11 18:06:44

问题


I just want to ask if there's a way to register dependencies in a simpliest way using unity.

    public class Module : IModule
    {
        IUnityContainer _container;
        IRegionManager _regionManager;

    public Module (IUnityContainer container, IRegionManager regionManager)
    {
        _container = container;
        _regionManager = regionManager;
    }

    public void initialize()
    {
      IRegion region = _regionManager.Regions[RegionNames.ContentRegion];
       _container.RegisterType<"InterfaceHERE", "CLASSHERE">();
    }

I do have 30-40 classes and interfaces, and I don't want to code it redundant. Are there any ways to code it in the simplest form? Like getting all classes and make a loop and register it?

Thanks!


回答1:


Since Unity 3.0 you can register your implementations in container using convention. Please see the details here, the code looks like below. You have to specify which types you want to auto-register, how (choose mapping), decide on their names and life time.

using (var container = new UnityContainer())
{
  container.RegisterTypes(
    AllClasses.FromLoadedAssemblies(),
    WithMapping.MatchingInterface,
    WithName.Default,
    WithLifetime.ContainerControlled);
}

If you are using Unity 2.0, then you have to use additional packages, see the nuget UnityConfiguration. Using this package you can scan for implementations and auto register them as below, please check the project documentation for details:

public class FooRegistry : UnityRegistry
{

    (...)

    Scan(scan =>
    {
            scan.AssembliesInBaseDirectory();
            scan.ForRegistries();
            scan.With<FirstInterfaceConvention>();
            scan.With<AddAllConvention>()
                .TypesImplementing<IHaveManyImplementations>();
            scan.With<SetAllPropertiesConvention>().OfType<ILogger>();
            scan.ExcludeType<FooService>();
    });
}


来源:https://stackoverflow.com/questions/46770190/register-dependency-unity

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