private void GenerateBaseExpression(ServiceBinding serviceBinding, CircularDependencyDetector circularDependencyDetector) { if (serviceBinding.BaseExpression == null) { lock (serviceBinding) { if (serviceBinding.BaseExpression == null) { if (serviceBinding.Expression == null) { var constructor = serviceBinding.ConstructorResolver.DynamicSelectConstructor(serviceBinding.ConcreteType, this); serviceBinding.Expression = serviceBinding.ConcreteType.ResolveConstructorExpression(constructor); } ParameterExpression[] parameters = serviceBinding.Expression.GetParameterExpressions().Where(x => x.Type != ExpressionGenerator.ScopeParameter.Type).ToArray(); var factories = new InstanceFactory[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { ParameterExpression parameter = parameters[i]; ServiceBinding child = GetDependency(parameter.Type).Default; InstanceFactory? factory = TryResolveDependency(parameter.Type, child, circularDependencyDetector); factories[i] = factory ?? throw (child.ResolveError ?? throw new NotImplementedException()); } serviceBinding.BaseExpression = _expressionGenerator.GenerateBaseExpression(serviceBinding, factories, _containerScope, Settings); } } } }
public ReadOnlyExpressionContext GenerateBaseExpression(ServiceBinding serviceBinding, InstanceFactory[] children, Scoped containerScope, SingularitySettings settings) { var context = new ExpressionContext(serviceBinding.Expression); if (serviceBinding.Expression is AbstractBindingExpression) { context.Expression = Expression.Constant(serviceBinding); return(context); } context.Expression = serviceBinding.Expression !is LambdaExpression lambdaExpression ? lambdaExpression.Body : serviceBinding.Expression; var parameterExpressionVisitor = new ParameterExpressionVisitor(context, children !); context.Expression = parameterExpressionVisitor.Visit(context.Expression); if (serviceBinding.NeedsDispose == DisposeBehavior.Always || settings.AutoDispose && serviceBinding.NeedsDispose != DisposeBehavior.Never && typeof(IDisposable).IsAssignableFrom(context.Expression.Type)) { MethodInfo method = Scoped.AddDisposableMethod.MakeGenericMethod(context.Expression.Type); MethodCallExpression methodCallExpression = Expression.Call(ScopeParameter, method, context.Expression); context.Expression = methodCallExpression; } if (serviceBinding.Finalizer != null) { MethodInfo method = Scoped.AddFinalizerMethod.MakeGenericMethod(context.Expression.Type); context.Expression = Expression.Call(ScopeParameter, method, context.Expression, Expression.Constant(serviceBinding)); } ApplyCaching(serviceBinding.Lifetime, containerScope, context); return(context); }
public ReadOnlyExpressionContext ApplyDecorators(Type dependencyType, ServiceBinding serviceBinding, InstanceFactory[] children, Expression[] decorators, Scoped containerScope) { ExpressionContext context = (ExpressionContext)(serviceBinding.BaseExpression ?? throw new ArgumentNullException("binding.BaseExpression")); if (decorators.Length > 0) { var body = new List <Expression>(); ParameterExpression instanceParameter = Expression.Variable(dependencyType, $"{dependencyType} instance"); body.Add(Expression.Assign(instanceParameter, Expression.Convert(context.Expression, dependencyType))); var decoratorExpressionVisitor = new DecoratorExpressionVisitor(children !, instanceParameter.Type); decoratorExpressionVisitor.PreviousDecorator = instanceParameter; foreach (Expression decorator in decorators) { Expression decoratorExpression = decorator; decoratorExpression = decoratorExpressionVisitor.Visit(decoratorExpression); decoratorExpressionVisitor.PreviousDecorator = decoratorExpression; } body.Add(decoratorExpressionVisitor.PreviousDecorator); if (body.Last().Type == typeof(void)) { body.Add(instanceParameter); } context.Expression = body.Count == 1 ? context.Expression : Expression.Block(new[] { instanceParameter }, body); ApplyCaching(serviceBinding.Lifetime, containerScope, context); } return(context); }
private void GenerateBaseExpression(ServiceBinding serviceBinding, CircularDependencyDetector circularDependencyDetector) { if (serviceBinding.BaseExpression == null) { lock (serviceBinding) { if (serviceBinding.BaseExpression == null) { ParameterExpression[] parameters = serviceBinding.Expression.GetParameterExpressions().Where(x => x.Type != ExpressionGenerator.ScopeParameter.Type).ToArray(); var factories = new InstanceFactory[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { ParameterExpression parameter = parameters[i]; ServiceBinding child = GetDependency(parameter.Type).Default; factories[i] = ResolveDependency(parameter.Type, child, circularDependencyDetector); } if (serviceBinding.ResolveError != null) { throw serviceBinding.ResolveError; } serviceBinding.BaseExpression = _expressionGenerator.GenerateBaseExpression(serviceBinding, factories, _containerScope, _settings); } } } }
public ReadOnlyExpressionContext GenerateBaseExpression(ServiceBinding serviceBinding, InstanceFactory[] children, Scoped containerScope, SingularitySettings settings) { var context = new ExpressionContext(serviceBinding.Expression); context.Expression = serviceBinding.Expression !is LambdaExpression lambdaExpression ? lambdaExpression.Body : serviceBinding.Expression ?? throw new ArgumentNullException(nameof(serviceBinding.Expression)); var parameterExpressionVisitor = new ParameterExpressionVisitor(context, children !); context.Expression = parameterExpressionVisitor.Visit(context.Expression); if (ShouldBeAutoDisposed(serviceBinding, context, settings)) { MethodInfo method = Scoped.AddDisposableMethod.MakeGenericMethod(context.Expression.Type); MethodCallExpression methodCallExpression = Expression.Call(ScopeParameter, method, context.Expression); context.Expression = methodCallExpression; } if (serviceBinding.Finalizer != null) { MethodInfo method = Scoped.AddFinalizerMethod.MakeGenericMethod(context.Expression.Type); context.Expression = Expression.Call(ScopeParameter, method, context.Expression, Expression.Constant(serviceBinding)); } serviceBinding.Lifetime.ApplyLifetimeOnExpression(containerScope, context); return(context); }
private InstanceFactory GenerateInstanceFactory(Type type, ServiceBinding serviceBinding, CircularDependencyDetector circularDependencyDetector) { lock (serviceBinding) { if (!serviceBinding.TryGetInstanceFactory(type, out InstanceFactory factory)) { if (serviceBinding.Expression is AbstractBindingExpression) { factory = new InstanceFactory(type, (ExpressionContext)serviceBinding.BaseExpression !, scoped => throw new AbstractTypeResolveException($"Cannot create a instance for type {type} since its registered as a abstract binding and not meant to be used directly.")); serviceBinding.Factories.Add(factory); return(factory); } Expression[] decorators = FindDecorators(type); ParameterExpression[] parameters = decorators.GetParameterExpressions().Where(x => x.Type != ExpressionGenerator.ScopeParameter.Type && x.Type != type).ToArray(); var childFactories = new InstanceFactory[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { ParameterExpression parameter = parameters[i]; ServiceBinding child = GetDependency(parameter.Type).Default; childFactories[i] = ResolveDependency(parameter.Type, child, circularDependencyDetector); } ReadOnlyExpressionContext context = _expressionGenerator.ApplyDecorators(type, serviceBinding, childFactories, decorators, _containerScope); factory = new InstanceFactory(type, context); serviceBinding.Factories.Add(factory); } return(factory); } }
private InstanceFactory ResolveDependency(Type type, ServiceBinding dependency, CircularDependencyDetector circularDependencyDetector) { circularDependencyDetector.Enter(type); GenerateBaseExpression(dependency, circularDependencyDetector); InstanceFactory factory = GenerateInstanceFactory(type, dependency, circularDependencyDetector); circularDependencyDetector.Leave(type); return(factory); }
public InstanceFactory Resolve(Type type) { if (Settings.ResolveErrorsExclusions.Match(type)) { return(TryResolve(type) !); } ServiceBinding serviceBinding = GetDependency(type).Default; return(ResolveDependency(type, serviceBinding)); }
public static void Binding(ServiceBinding binding, string id, string name, string description, string uri, string serviceId) { Assert.AreEqual(id ?? "", binding.Id ?? ""); Assert.AreEqual(name ?? "", binding.Name.GetValue() ?? ""); Assert.AreEqual(name ?? "", binding.Name.GetValue("en-US") ?? ""); Assert.AreEqual(description ?? "", binding.Description.GetValue() ?? ""); Assert.AreEqual(description ?? "", binding.Description.GetValue("en-US") ?? ""); Assert.AreEqual(uri, binding.AccessURI ?? ""); Assert.AreEqual(serviceId, binding.Service ?? ""); }
private InstanceFactory ResolveDependency(Type type, ServiceBinding dependency) { InstanceFactory?factory = TryResolveDependency(type, dependency); if (factory != null) { return(factory); } throw dependency.ResolveError ?? throw new NotImplementedException("Factory was null but the resolve exception was null as well"); }
private IEnumerable <ServiceBinding> Resolve <TElement>(IInstanceFactoryResolver resolver, Type type) { foreach (InstanceFactory instanceFactory in resolver.TryResolveAll(typeof(TElement))) { var newBinding = new ServiceBinding(type, BindingMetadata.GeneratedInstance, instanceFactory.Context.Expression, instanceFactory.Context.Expression.Type, ConstructorResolvers.Default, Lifetimes.Transient); var expression = Expression.Lambda <Func <TElement> >(ExpressionCompiler.OptimizeExpression(instanceFactory.Context)); Func <Scoped, Expression <Func <TElement> > > del = scoped => expression; // we need to put this in a variable of this type or cast it else the static return type of the delegate will turn into a object.. var factory = new InstanceFactory(type, new ExpressionContext(expression), del); newBinding.Factories.Add(factory); yield return(newBinding); } }
private InstanceFactory[] ResolveParameters(ParameterExpression[] parameters, CircularDependencyDetector circularDependencyDetector) { var factories = new InstanceFactory[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { ParameterExpression parameter = parameters[i]; ServiceBinding child = GetDependency(parameter.Type).Default; InstanceFactory? factory = TryResolveDependency(parameter.Type, child, circularDependencyDetector); factories[i] = factory ?? throw (child.ResolveError ?? throw new NotImplementedException()); } return(factories); }
public InstanceFactory Resolve(Type type) { if (Settings.ResolveErrorsExclusions.Match(type)) { // TODO Bit of a hack since the signature of this method means it cannot return null.. However this is needed for integration with microsoft dependency injection. // The reason this is needed is because the of way IServiceProvider is used in ASP .NET it has to return null in some cases instead of throwing a exception. // Ideally IServiceProvider should have different methods for this so this hack is not needed. return(TryResolve(type) ?? new InstanceFactory(type, new ReadOnlyExpressionContext(new ExpressionContext(Expression.Constant(null))))); } ServiceBinding serviceBinding = GetBinding(type); return(ResolveDependency(type, serviceBinding)); }
private InstanceFactory GenerateInstanceFactory(Type type, ServiceBinding serviceBinding, CircularDependencyDetector circularDependencyDetector) { lock (serviceBinding) { if (!serviceBinding.TryGetInstanceFactory(type, out InstanceFactory factory)) { Expression[] decorators = FindDecorators(type); ParameterExpression[] parameters = decorators.GetParameterExpressions().Where(x => x.Type != ExpressionGenerator.ScopeParameter.Type && x.Type != type).ToArray(); InstanceFactory[] factories = ResolveParameters(parameters, circularDependencyDetector); ReadOnlyExpressionContext context = _expressionGenerator.ApplyDecorators(type, serviceBinding, factories, decorators, _containerScope); factory = new InstanceFactory(type, context); serviceBinding.Factories.Add(factory); } return(factory); } }
public IEnumerable <ServiceBinding> Resolve(IResolverPipeline graph, Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Lazy <>)) { Type funcType = typeof(Func <>).MakeGenericType(type.GenericTypeArguments[0]); Type lazyType = typeof(Lazy <>).MakeGenericType(type.GenericTypeArguments[0]); ConstructorInfo constructor = lazyType.GetConstructor(new[] { funcType }); foreach (InstanceFactory factory in graph.ResolveAll(funcType)) { NewExpression baseExpression = Expression.New(constructor, factory.Expression); var newBinding = new ServiceBinding(type, new BindingMetadata(), baseExpression); newBinding.Factories.Add(new InstanceFactory(type, baseExpression)); yield return(newBinding); } } }
/// <inheritdoc /> public IEnumerable <ServiceBinding> Resolve(IInstanceFactoryResolver resolver, Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Lazy <>)) { Type funcType = typeof(Func <>).MakeGenericType(type.GenericTypeArguments[0]); Type lazyType = typeof(Lazy <>).MakeGenericType(type.GenericTypeArguments[0]); ConstructorInfo constructor = lazyType.GetConstructor(new[] { funcType }); foreach (InstanceFactory factory in resolver.TryResolveAll(funcType)) { var context = (ExpressionContext)factory.Context; context.Expression = Expression.New(constructor, factory.Context.Expression); var newBinding = new ServiceBinding(type, BindingMetadata.GeneratedInstance, context.Expression, type, ConstructorResolvers.Default, Lifetimes.Transient); newBinding.Factories.Add(new InstanceFactory(type, context)); yield return(newBinding); } } }
private InstanceFactory?TryResolveDependency(Type type, ServiceBinding dependency, CircularDependencyDetector circularDependencyDetector) { try { Settings.Logger.Log($"{nameof(TryResolveDependency)} for {type}", circularDependencyDetector.Count); circularDependencyDetector.Enter(type); GenerateBaseExpression(dependency, circularDependencyDetector); InstanceFactory factory = GenerateInstanceFactory(type, dependency, circularDependencyDetector); return(factory); } catch (Exception e) { dependency.ResolveError = new DependencyResolveException(type, dependency, e); return(null); } finally { circularDependencyDetector.Leave(type); } }
public void AddBinding(ServiceBinding serviceBinding) { SinglyLinkedListNode <Type>?currentNode = serviceBinding.ServiceTypes; while (currentNode != null) { Type type = currentNode.Value; if (!Registrations.TryGetValue(type, out Registration registration)) { registration = new Registration(serviceBinding); Registrations.Add(type, registration); } else { registration.AddBinding(serviceBinding); } currentNode = currentNode.Next; } }
public void RegisterServices() { var serviceCollection = new ServiceCollection(); serviceCollection.AddTransient <IRepositoryTransient1, RepositoryTransient1>(); var builder = new ContainerBuilder(builder => { builder.RegisterServices(serviceCollection); }); RegistrationStore registrationStore = builder.Registrations; KeyValuePair <Type, Registration> registration = Assert.Single(registrationStore.Registrations); Assert.Empty(registrationStore.Decorators); ServiceBinding serviceBinding = Assert.Single(registration.Value.Bindings); Assert.Equal(typeof(IRepositoryTransient1), registration.Key); Assert.Equal(typeof(RepositoryTransient1), serviceBinding.Expression?.Type); }
/// <inheritdoc /> public IEnumerable <ServiceBinding> Resolve(IResolverPipeline graph, Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Expression <>) && type.GenericTypeArguments.Length == 1) { Type funcType = type.GenericTypeArguments[0]; if (funcType.GetGenericTypeDefinition() == typeof(Func <>) && funcType.GenericTypeArguments.Length == 1) { Type dependencyType = funcType.GenericTypeArguments[0]; MethodInfo method = GenericCreateLambdaMethod.MakeGenericMethod(dependencyType); foreach (InstanceFactory instanceFactory in graph.TryResolveAll(dependencyType)) { var newBinding = new ServiceBinding(type, BindingMetadata.GeneratedInstance, instanceFactory.Context.Expression, instanceFactory.Context.Expression.Type, graph.Settings.ConstructorResolver); var expression = (Expression)method.Invoke(null, new object[] { instanceFactory.Context }); var factory = new InstanceFactory(type, new ExpressionContext(expression), scoped => expression); newBinding.Factories.Add(factory); yield return(newBinding); } } } }
private void GenerateBaseExpression(ServiceBinding serviceBinding, CircularDependencyDetector circularDependencyDetector) { if (serviceBinding.BaseExpression == null) { lock (serviceBinding) { if (serviceBinding.BaseExpression == null) { if (serviceBinding.Expression == null) { var constructor = serviceBinding.ConstructorResolver.DynamicSelectConstructor(serviceBinding.ConcreteType, this); serviceBinding.Expression = serviceBinding.ConcreteType.ResolveConstructorExpression(constructor); } ParameterExpression[] parameters = serviceBinding.Expression.GetParameterExpressions().Where(x => x.Type != ExpressionGenerator.ScopeParameter.Type).ToArray(); InstanceFactory[] factories = ResolveParameters(parameters, circularDependencyDetector); serviceBinding.BaseExpression = _expressionGenerator.GenerateBaseExpression(serviceBinding, factories, _containerScope, Settings); } } } }
public static ServiceConfiguration ApplyCustomAuthentication (this ServiceConfiguration config, Type serviceType, string address) { config.Credentials.IdentityConfiguration = CreateIdentityConfiguration(); config.Credentials.UseIdentityConfiguration = true; config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true }); config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); var behavior = new ServiceAuthorizationBehavior { PrincipalPermissionMode = PrincipalPermissionMode.Always }; config.Description.Behaviors.Add(behavior); config.AddServiceEndpoint(serviceType, ServiceBinding.CreateBinding(), address); return(config); }
private InstanceFactory?TryResolveDependency(Type type, ServiceBinding dependency, CircularDependencyDetector circularDependencyDetector) { try { Settings.Logger.Log($"{nameof(TryResolveDependency)} for {type}", circularDependencyDetector.Count); circularDependencyDetector.Enter(type); if (type.IsGenericType && type.ContainsGenericParameters) { throw new OpenGenericTypeResolveException($"Cannot create a instance for type {type} since its registered as a abstract binding and not meant to be used directly."); } GenerateBaseExpression(dependency, circularDependencyDetector); InstanceFactory factory = GenerateInstanceFactory(type, dependency, circularDependencyDetector); return(factory); } catch (Exception e) { dependency.ResolveError = new DependencyResolveException(type, dependency, e); return(null); } finally { circularDependencyDetector.Leave(type); } }
public InstanceFactory Resolve(Type type) { ServiceBinding serviceBinding = GetDependency(type).Default; return(ResolveDependency(type, serviceBinding)); }
public async Task StartAsync(Application application) { await PurgeFromPreviousRun(); var containers = new List <Service>(); foreach (var s in application.Services) { if (s.Value.Description.RunInfo is DockerRunInfo) { containers.Add(s.Value); } } if (containers.Count == 0) { return; } var proxies = new List <Service>(); foreach (var service in application.Services.Values) { if (service.Description.RunInfo is DockerRunInfo || service.Description.Bindings.Count == 0) { continue; } // Inject a proxy per non-container service. This allows the container to use normal host names within the // container network to talk to services on the host var proxyContanier = new DockerRunInfo($"mcr.microsoft.com/dotnet/core/sdk:3.1", "dotnet Microsoft.Tye.Proxy.dll") { WorkingDirectory = "/app", NetworkAlias = service.Description.Name, Private = true }; var proxyLocation = Path.GetDirectoryName(typeof(Microsoft.Tye.Proxy.Program).Assembly.Location); proxyContanier.VolumeMappings.Add(new DockerVolume(proxyLocation, name: null, target: "/app")); var proxyDescription = new ServiceDescription($"{service.Description.Name}-proxy", proxyContanier); foreach (var binding in service.Description.Bindings) { if (binding.Port == null) { continue; } var b = new ServiceBinding() { ConnectionString = binding.ConnectionString, Host = binding.Host, ContainerPort = binding.ContainerPort, Name = binding.Name, Port = binding.Port, Protocol = binding.Protocol }; b.ReplicaPorts.Add(b.Port.Value); proxyDescription.Bindings.Add(b); } var proxyContanierService = new Service(proxyDescription); containers.Add(proxyContanierService); proxies.Add(proxyContanierService); } string?dockerNetwork = null; if (!string.IsNullOrEmpty(application.Network)) { var dockerNetworkResult = await ProcessUtil.RunAsync("docker", $"network ls --filter \"name={application.Network}\" --format \"{{{{.ID}}}}\"", throwOnError : false); if (dockerNetworkResult.ExitCode != 0) { _logger.LogError("{Network}: Run docker network ls command failed", application.Network); throw new CommandException("Run docker network ls command failed"); } if (!string.IsNullOrWhiteSpace(dockerNetworkResult.StandardOutput)) { _logger.LogInformation("The specified network {Network} exists", application.Network); dockerNetwork = application.Network; } else { _logger.LogWarning("The specified network {Network} doesn't exist.", application.Network); application.Network = null; } } // We're going to be making containers, only make a network if we have more than one (we assume they'll need to talk) if (string.IsNullOrEmpty(dockerNetwork) && containers.Count > 1) { dockerNetwork = "tye_network_" + Guid.NewGuid().ToString().Substring(0, 10); application.Items["dockerNetwork"] = dockerNetwork; _logger.LogInformation("Creating docker network {Network}", dockerNetwork); var command = $"network create --driver bridge {dockerNetwork}"; _logger.LogInformation("Running docker command {Command}", command); var dockerNetworkResult = await ProcessUtil.RunAsync("docker", command, throwOnError : false); if (dockerNetworkResult.ExitCode != 0) { _logger.LogInformation("Running docker command with exception info {ExceptionStdOut} {ExceptionStdErr}", dockerNetworkResult.StandardOutput, dockerNetworkResult.StandardError); throw new CommandException("Run docker network create command failed"); } } // Stash information outside of the application services application.Items[typeof(DockerApplicationInformation)] = new DockerApplicationInformation(dockerNetwork, proxies); var tasks = new Task[containers.Count]; var index = 0; foreach (var s in containers) { var docker = (DockerRunInfo)s.Description.RunInfo !; tasks[index++] = StartContainerAsync(application, s, docker, dockerNetwork); } await Task.WhenAll(tasks); }
/// <summary> /// 添加保存设备信息 /// </summary> /// <param name="device"></param> /// <returns></returns> public ActionResult SaveDeviceInfo(Device device) { try { using (var db = new MbContext()) { #region 判断厂家 var m = new Manufacturer(); if (!string.IsNullOrEmpty(device.ManufacturerName)) { m = db.Manufacturer.FirstOrDefault(t => t.Name == device.ManufacturerName); if (m == null) { m = db.Manufacturer.Add(new Manufacturer { Name = device.ManufacturerName, CreateTime = DateTime.Now }); } } #endregion #region 判断品牌 var b = new Brand(); if (!string.IsNullOrEmpty(device.BrandName)) { b = db.Brand.FirstOrDefault(t => t.Name == device.BrandName); if (b == null) { b = db.Brand.Add(new Brand { ManufacturerId = m.ManufacturerId, Name = device.BrandName, CreateTime = DateTime.Now }); } device.BrandId = b.BrandId; } #endregion #region 判断区域 var a = new Area(); if (!string.IsNullOrEmpty(device.AreaName)) { a = db.Area.FirstOrDefault(t => t.Name == device.AreaName); if (a == null) { a = db.Area.Add(new Area { LevelDeep = 0, Name = device.AreaName, Code = "0", CreateTime = DateTime.Now }); } device.AreaId = a.AreaId; } #endregion #region 类目 var c = new Category(); if (!string.IsNullOrEmpty(device.CategoryName)) { c = db.Category.FirstOrDefault(t => t.Name == device.CategoryName); if (c == null) { c = db.Category.Add(new Category { LevelDeep = 0, Name = device.CategoryName, SortField = 999, CreateTime = DateTime.Now }); } device.CategoryId = c.CategoryId; } #endregion device.LastUpdateTime = DateTime.Now; device.CreateTime = DateTime.Now; if (device.QRCode != null && device.QRCode != "") { //判断二维码是否已经存在 var dInfo = db.Device.Where(t => t.QRCode == device.QRCode).FirstOrDefault(); if (dInfo != null && device.DeviceId != dInfo.DeviceId) { return(Json(new { success = "该二维码已经存在", deviceId = device.DeviceId })); } } db.Device.AddOrUpdate(device); int result = db.SaveChanges(); if (device.pictureId != null && device.pictureId.Length > 0) { new PictureService().EditPicture(device.pictureId, device.DeviceId.ToString()); } if (device.ServiceCompanyId != null && device.ServiceCompanyId.Length > 0) { //往ServiceBinding里面插数据 for (int i = 0; i < device.ServiceCompanyId.Length; i++) { var category = new ServiceBinding { BindingType = BindingServiceType.Equipment, Content = device.DeviceId.ToString(), OutNote = string.Empty, ServiceCompanyId = device.ServiceCompanyId[i], UseCompanyId = (device.UseCompanyId ?? ""), CreateTime = DateTime.Now }; db.ServiceBinding.AddOrUpdate(category); var deviceContract = new DeviceContract { DeviceId = device.DeviceId, Sort = i, ServiceCompanyId = device.ServiceCompanyId[i] }; db.DeviceContract.AddOrUpdate(deviceContract); } result = db.SaveChanges(); } if (result > 0) { return(Json(new { success = "操作成功", deviceId = device.DeviceId }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { error = "操作失败,请稍后重试" }, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { Logger.Error("添加设备异常", ex); return(Json(new { error = "添加设备异常" }, JsonRequestBehavior.AllowGet)); } }
private bool ShouldBeAutoDisposed(ServiceBinding serviceBinding, ExpressionContext context, SingularitySettings settings) { return(serviceBinding.NeedsDispose == ServiceAutoDispose.Always || serviceBinding.NeedsDispose != ServiceAutoDispose.Never && typeof(IDisposable).IsAssignableFrom(context.Expression.Type) && settings.AutoDisposeLifetimes.Contains(serviceBinding.Lifetime.GetType())); }
static void Main(string[] args) { var contracts = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "SmartTools.Service.Contract" && t.IsPublic); var services = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "SmartTools.Service.Implementation" && t.IsPublic); foreach (var service in services) { Uri url = new Uri($"http://127.0.0.1:{Configuration.Port}/{service.Name}"); ServiceHost host = new ServiceHost(service, url); host.Opened += (object sender, EventArgs e) => { Console.WriteLine("[SmartTools Service] Opened!"); }; host.Closed += (object sender, EventArgs e) => { Console.WriteLine("[SmartTools Service] closed!"); }; host.AddServiceEndpoint(contracts.Where(c => c.Name.Contains(service.Name)).FirstOrDefault(), ServiceBinding.Create <WebHttpBinding>(), url); host.LoadBehaviors(); host.InitBehaviors(); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); var communicationObject = host as ICommunicationObject; communicationObject.Open(); _ServiceQueue.Enqueue(communicationObject); } while (true) { var input = Console.ReadLine(); if (input.Equals("Close Service", StringComparison.OrdinalIgnoreCase)) { while (true) { ICommunicationObject serviceHost; bool isPeekSuccess = _ServiceQueue.TryPeek(out serviceHost); if (!isPeekSuccess) { break; } serviceHost.Close(); } break; } } }
private InstanceFactory ResolveDependency(Type type, ServiceBinding dependency) => ResolveDependency(type, dependency, new CircularDependencyDetector());
/// <summary> /// Constructs a new <see cref="DependencyResolveException"/> /// </summary> /// <param name="type"></param> /// <param name="serviceBinding"></param> /// <param name="inner"></param> public DependencyResolveException(Type type, ServiceBinding serviceBinding, Exception inner) : base($"Failed to resolve dependency {type} for registration {serviceBinding.BindingMetadata}", inner) { }