public object GetService(Type serviceType, string contract = null)
 {
     try
     {
         return(string.IsNullOrEmpty(contract)
             ? _container.Resolve(serviceType)
             : _container.ResolveNamed(contract, serviceType));
     }
     catch (DependencyResolutionException)
     {
         return(null);
     }
 }
Exemplo n.º 2
0
        protected override object GetInstance(Type service, string key)
        {
            object obj = key == null?_container.ResolveOptional(service) : _container.ResolveNamed(key, service);

            _logger.Info(string.Format("{0} resolved", service));
            return(obj);
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var containerBuilder = new ContainerBuilder();

            //models
            containerBuilder.RegisterType <Calculator>().As <ICalculator>().SingleInstance();
            containerBuilder.RegisterType <Logger>().As <ILogger>().SingleInstance();
            containerBuilder.RegisterType <Auth>().As <IAuth>().SingleInstance();
            containerBuilder.RegisterType <ModelFacade>().As <IModelFacade>().SingleInstance();

            //controllers
            containerBuilder.RegisterType <CalcController>().As <ICalcController>().SingleInstance();
            containerBuilder.RegisterType <LoginController>().As <ILoginController>().SingleInstance();
            containerBuilder.RegisterType <WinFormsViewHandler>().As <IViewHandler>().SingleInstance();

            //views
            containerBuilder.RegisterType <ErrorForm <ILoginController> >().As <IView>().Named <IView>("LoginError");
            containerBuilder.RegisterType <LoginForm>().As <IView>().Named <IView>("Login");
            containerBuilder.RegisterType <MainForm>().As <IView>().Named <IView>("Main");

            //infrastructure
            containerBuilder.RegisterType <AutofacContainer>().As <Controllers.IContainer>().SingleInstance();
            containerBuilder.Register(context => autofacContainer).As <Autofac.IContainer>();

            autofacContainer = containerBuilder.Build();

            Application.Run((Form)autofacContainer.ResolveNamed <IView>("Login"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 初始化Opc服务
        /// </summary>
        private IOpcClient OpcFinder(string opcName)
        {
            ContainerBuilder builder = new ContainerBuilder();
            Type             opcType;
            Type             baseType = typeof(IOpcClient);

            // 获取所有OPC相关类库的程序集
            Assembly[] assemblies = GetOpcAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    opcType = assembly.GetType(opcName);
                    if (opcType != null)
                    {
                        builder.RegisterType(opcType)
                        .Named <IOpcClient>(opcName)
                        .SingleInstance();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            Autofac.IContainer container = builder.Build();
            IOpcClient         opcClient = container.ResolveNamed <IOpcClient>(opcName);

            return(opcClient);
        }
Exemplo n.º 5
0
 public T GetService <T>(string name)
 {
     if (string.IsNullOrEmpty(name))
     {
         return((T)_container?.Resolve(typeof(T)));
     }
     return((T)_container?.ResolveNamed(name, typeof(T)));
 }
Exemplo n.º 6
0
 /// <summary>
 /// 获取服务
 /// </summary>
 private object GetService(Type type, string name)
 {
     if (name == null)
     {
         return(_container.Resolve(type));
     }
     return(_container.ResolveNamed(name, type));
 }
Exemplo n.º 7
0
 public TInterface Get <TInterface>(string typeName)
 {
     if (container == null)
     {
         throw new Exception("IContainer is null");
     }
     return(container.ResolveNamed <TInterface>(typeName));
 }
Exemplo n.º 8
0
        /// <summary>
        /// 创建对象
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="name">服务名称</param>
        /// <returns></returns>
        public object Create(Type type, string name = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(Container.Resolve(type));
            }

            return(Container.ResolveNamed(name, type));
        }
Exemplo n.º 9
0
        private void AutoFacBenchmark(IContainer container)
        {
            using (container.BeginLifetimeScope())
            {
                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine("Continuing with AutoFac tests");
                Stopwatch timer;
                TimeSpan  elapsed5;
                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.Resolve <ITestClass>();
                }
                timer.Stop();
                elapsed5  = timer.Elapsed;
                Singleton = new KeyValuePair <TimeSpan, TimeSpan>(Singleton.Key, elapsed5);
                Console.WriteLine("{0} instances created with singleton resolves  in {1} ms", Iterations, elapsed5.TotalMilliseconds);


                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.Resolve <ITestClass2>();
                }
                timer.Stop();
                elapsed5  = timer.Elapsed;
                Transient = new KeyValuePair <TimeSpan, TimeSpan>(Transient.Key, elapsed5);
                Console.WriteLine("{0} instances created with transient resolves  in {1} ms", Iterations, elapsed5.TotalMilliseconds);

                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.ResolveNamed <ITestClass>(ServiceName);
                }
                timer.Stop();
                elapsed5 = timer.Elapsed;

                Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations,
                                  elapsed5.TotalMilliseconds);

                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.Resolve <ITestClass3>();
                    if (instance.TClass == null)
                    {
                        Console.WriteLine("Injection failed");
                    }
                }
                timer.Stop();
                elapsed5 = timer.Elapsed;
                TransientWithInjection = new KeyValuePair <TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5);
                Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds);
            }
        }
Exemplo n.º 10
0
 protected override object GetInstance(Type service, string key)
 {
     if (string.IsNullOrWhiteSpace(key))
     {
         return(container.Resolve(service));
     }
     else
     {
         return(container.ResolveNamed(key, service));
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// 从上下文检索服务
 /// </summary>
 /// <typeparam name="T">T</typeparam>
 /// <param name="serviceName">服务名称</param>
 /// <returns></returns>
 public T Resolve <T>(string serviceName = null) where T : class
 {
     if (string.IsNullOrEmpty(serviceName))
     {
         return(_container.Resolve <T>());
     }
     else
     {
         return(_container.ResolveNamed <T>(serviceName));
     }
 }
 public TInterface Get <TInterface>(string typeName)
 {
     if (container == null)
     {
         throw new Exception("IContainer is null");
     }
     if (container.IsRegisteredWithName <TInterface>(typeName))
     {
         return(container.ResolveNamed <TInterface>(typeName));
     }
     else
     {
         return(default);
Exemplo n.º 13
0
        /// <summary>
        /// 从上下文检索服务
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="serviceName">服务名称</param>
        /// <returns></returns>
        public T Resolve <T>(string serviceName)
        {
            if (this._resolver == null)
            {
                if (_container.TryResolve <IDependencyResolver>(out IDependencyResolver resolver))
                {
                    this._resolver = resolver;
                }
            }

            if (this._resolver != null)
            {
                return(this._resolver.Resolve <T>(serviceName));
            }

            return(serviceName.IsEmpty() ? _container.Resolve <T>() : _container.ResolveNamed <T>(serviceName));
        }
Exemplo n.º 14
0
        /// <summary>
        /// 重新初始化自定义服务
        /// </summary>
        private void ReservicesInit()
        {
            //string path = Application.StartupPath;
            //var dfd = GetServicePathBinding(path);
            //SetServicePathBinding(path, "Services/ServiceForPRARE;Services/ServiceForEasySocketService");
            ContainerBuilder builder      = new ContainerBuilder();
            List <string>    serviceNames = new List <string>();
            Type             baseType     = typeof(IDependency);

            // 获取所有相关类库的程序集
            Assembly[]            assemblies         = GetApiAssemblies();
            List <NamedParameter> ListNamedParameter = new List <NamedParameter>()
            {
                new NamedParameter("opcClient", client)
            };

            foreach (Assembly assembly in assemblies)
            {
                IEnumerable <Type> types = assembly.GetTypes()
                                           .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract);
                serviceNames.AddRange(types.Select(type => type.Name));
                foreach (Type type in types)
                {
                    builder.RegisterType(type)
                    .Named <ITagService>(type.Name)
                    .WithParameters(ListNamedParameter)
                    .SingleInstance();
                }
            }

            //构建容器来完成注册并准备对象解析。
            Autofac.IContainer container = builder.Build();
            // 现在您可以使用Autofac解决服务问题。例如,这一行将执行注册到IConfigReader服务的lambda表达式。
            using (var scope = container.BeginLifetimeScope())
            {
                tagServices.Clear();
                foreach (var serviceName in serviceNames)
                {
                    ITagService tagService = container.ResolveNamed <ITagService>(serviceName);
                    tagService.MsgHandle = AddMsgToList;
                    //tagService.Connect();
                    tagServices.Add(serviceName, tagService);
                    AddMsgToList(serviceName + " > " + "[Loaded]");
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 初始化Opc服务
        /// </summary>
        private IOpcClient OpcFinder(string opcName)
        {
            ContainerBuilder builder  = new ContainerBuilder();
            Type             opcType  = null;
            Type             baseType = typeof(IOpcClient);

            // 获取所有OPC相关类库的程序集
            Assembly[] assemblies = GetOpcAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    // opcType = assembly.GetTypes()
                    //.Where(type => type.Name == opcName && baseType.IsAssignableFrom(type) && !type.IsAbstract).FirstOrDefault();
                    opcType = assembly.GetType(opcName);
                    if (opcType != null)
                    {
                        builder.RegisterType(opcType)
                        .Named <IOpcClient>(opcName)
                        .SingleInstance();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    AddMsgToList(ex.ToString());
                }
            }
            //Autofac.IContainer container = builder.Build();
            //IOpcClient opcClient = container.ResolveNamed<IOpcClient>(opcName);

            IOpcClient opcClient;

            //构建容器来完成注册并准备对象解析。
            Autofac.IContainer container = builder.Build();
            // 现在您可以使用Autofac解决服务问题。例如,这一行将执行注册到IConfigReader服务的lambda表达式。
            using (var scope = container.BeginLifetimeScope())
            {
                opcClient = container.ResolveNamed <IOpcClient>(opcName);
            }
            return(opcClient);
        }
Exemplo n.º 16
0
 protected override object GetInstance(Type service, string key)
 {
     if (service == null)
     {
         throw new ArgumentNullException(nameof(service));
     }
     if (string.IsNullOrWhiteSpace(key))
     {
         if (_container.IsRegistered(service))
         {
             return(_container.Resolve(service));
         }
     }
     else
     {
         if (_container.IsRegisteredWithName(key, service))
         {
             return(_container.ResolveNamed(key, service));
         }
     }
     throw new Exception($"Could not locate an instances of '{key ?? service.Name}'.");
 }
Exemplo n.º 17
0
        private void AutoFacBenchmark(IContainer container)
        {
            using (container.BeginLifetimeScope())
            {
                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine("Continuing with AutoFac tests");
                Stopwatch timer;
                TimeSpan elapsed5;
                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.Resolve<ITestClass>();
                }
                timer.Stop();
                elapsed5 = timer.Elapsed;
                Singleton = new KeyValuePair<TimeSpan, TimeSpan>(Singleton.Key, elapsed5);
                Console.WriteLine("{0} instances created with singleton resolves  in {1} ms", Iterations, elapsed5.TotalMilliseconds);


                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.Resolve<ITestClass2>();
                }
                timer.Stop();
                elapsed5 = timer.Elapsed;
                Transient = new KeyValuePair<TimeSpan, TimeSpan>(Transient.Key, elapsed5);
                Console.WriteLine("{0} instances created with transient resolves  in {1} ms", Iterations, elapsed5.TotalMilliseconds);

                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.ResolveNamed<ITestClass>(ServiceName);
                }
                timer.Stop();
                elapsed5 = timer.Elapsed;

                Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations,
                    elapsed5.TotalMilliseconds);

                timer = Stopwatch.StartNew();
                for (int i = 0; i < Iterations; i++)
                {
                    var instance = container.Resolve<ITestClass3>();
                    if (instance.TClass == null) Console.WriteLine("Injection failed");
                }
                timer.Stop();
                elapsed5 = timer.Elapsed;
                TransientWithInjection = new KeyValuePair<TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5);
                Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds);
            }
        }
Exemplo n.º 18
0
 public T GetObject <T>(string name) => container.ResolveNamed <T>(name);
 public IView GetCalcErrorView() => container.ResolveNamed <IView>("CalcError");
Exemplo n.º 20
0
 public TService ResolveNamed <TService>(string serviceName) where TService : class
 {
     return(_container.ResolveNamed <TService>(serviceName));
 }
 /// <summary>
 /// 利用类型推断和扩展方法简化Resolve的写法
 /// </summary>
 /// <typeparam name="TComponent"></typeparam>
 /// <param name="component"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static TComponent ResolveNamed <TComponent>(this TComponent component, string name)
 {
     return(Container.ResolveNamed <TComponent>(name));
 }
Exemplo n.º 22
0
 public static TService ResolveNamed <TService>(string serviceName, params Parameter[] parameters)
 {
     ThrowIfNotInitialized();
     return(_container.ResolveNamed <TService>(serviceName, parameters));
 }
Exemplo n.º 23
0
 public T Resolve <T>()
     where T : class
 {
     return(_container.ResolveNamed <T>("WebService"));
 }
Exemplo n.º 24
0
 public override object ResolveNamed(string serviceName, Type serviceType)
 {
     return(_container.ResolveNamed(serviceName, serviceType));
 }
Exemplo n.º 25
0
 public static T GetFromFac <T>(string name)
 {
     return(_container.ResolveNamed <T>(name));
 }
        /// <inheritdoc />
        /// <summary>
        /// Resolve a named instance of type T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public T Resolve <T>(string key)
        {
            _Log.DebugFormat("Resolve instance of type {0} with name {1}", typeof(T), key);

            return(_InnerContainer.ResolveNamed <T>(key));
        }