using Mogafa.Common.Ioc; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zenject; namespace Mogafa.Unity.Common.Ioc.Zenject { public class ZenjectContainer : IContainer { private DiContainer container; public void Build() { container = new DiContainer(); } private void BinderLife(FromBinder binder, LifeStyle life) { if (life == LifeStyle.Singleton) { binder.AsSingle(); } else { binder.AsTransient(); } } public void RegisterType(Type implementationType, string serviceName = null, LifeStyle life = LifeStyle.Singleton) { var binder = container.Bind(implementationType); BinderLife(binder, life); if (!string.IsNullOrEmpty(serviceName)) { binder.WithId(serviceName); } binder.ToSelf(); } public void RegisterType(Type serviceType, Type implementationType, string serviceName = null, LifeStyle life = LifeStyle.Singleton) { var binder = container.Bind(serviceType); BinderLife(binder, life); if (!string.IsNullOrEmpty(serviceName)) { binder.WithId(serviceName); } binder.To(implementationType); } public TService Resolve() where TService : class { return container.Resolve(); } public object Resolve(Type serviceType) { return container.Resolve(serviceType); } public TService ResolveNamed(string serviceName) where TService : class { return container.ResolveId(serviceName); } public object ResolveNamed(string serviceName, Type serviceType) { return container.RebindId(serviceType, serviceName); } public bool TryResolve(out TService instance) where TService : class { instance = container.TryResolve(); return instance != null; } public bool TryResolve(Type serviceType, out object instance) { instance = container.TryResolve(serviceType); return instance != null; } public bool TryResolveNamed(string serviceName, Type serviceType, out object instance) { instance = container.TryResolveId(serviceType, serviceName); return instance != null; } void IContainer.Register(string serviceName, LifeStyle life) { var binder = container.Bind().To(); BinderLife(binder, life); } void IContainer.RegisterInstance(TImplementer instance, string serviceName) { container.Bind().To().FromInstance(instance).AsSingle(); } } }