register dependency Unity

2019-08-19 06:21发布

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条回答
Root(大扎)
2楼-- · 2019-08-19 07:10

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>();
    });
}
查看更多
登录 后发表回答