C# Azure服务结构参与者依赖项注入

C# Azure服务结构参与者依赖项注入,c#,dependency-injection,azure-service-fabric,actor,C#,Dependency Injection,Azure Service Fabric,Actor,有没有办法将依赖项注入Azure Service Fabric Actor的构造函数 不久前,dotPeek在这方面做了一些研究(试图从每次调用的Autofac生存期范围中解析参与者),我认为关键在于创建您自己的无状态ActorServiceFactory实现,以及您自己的扩展方法来注册参与者。尽管工厂类标记为内部,但其接口(IStatelessServiceFactory)及其创建的服务类型(无状态ActorServiceInstance)都是公共的。不幸的是,它看起来不像无状态ActorSe

有没有办法将依赖项注入Azure Service Fabric Actor的构造函数

不久前,dotPeek在这方面做了一些研究(试图从每次调用的Autofac生存期范围中解析参与者),我认为关键在于创建您自己的无状态ActorServiceFactory实现,以及您自己的扩展方法来注册参与者。尽管工厂类标记为内部,但其接口(IStatelessServiceFactory)及其创建的服务类型(无状态ActorServiceInstance)都是公共的。不幸的是,它看起来不像无状态ActorServiceInstance被设计成可扩展的(我希望这只是一个疏忽)

不幸的是,WcfActorCommunicationProvider也被标记为internal,因此您几乎必须从头开始创建自己的管道:

  • 实现您自己的远程服务工厂
  • 实现您自己的IStatelessServiceInstance,IActorService
  • 实现您自己的IActorCommunicationProvider
  • 实现您自己的IActorHost
  • 看起来真的不值得再努力了,是吗-/


    那就是我现在放弃的地方。考虑到公共API的相对不成熟性,我认为现在不值得尝试推出自己的API,因为如果这种功能出现,它们可能会破坏您自己实现的任何功能。

    为什么不在actor中使用一些根元素字段,并从容器中解析它,并在Actor的构造函数中注入依赖项?如果这是一个错误的决定,请解释原因:

    public class StatelessActor2 : Actor, IStatelessActor2
    {
        private ConfiguredContainer _container;
        private IRootElement _rootElement;
    
        public StatelessActor2()
    
        {
            _container = new ConfiguredContainer(); //... container is configured in it's constructor
            _rootElement = _container.Resolve<IRootElement>();
        }
    
        public async Task<string> DoWorkAsync()
        {
            // Working with a RootElement with all dependencies are injected..
            return await Task.FromResult(_rootElement.WorkingWithInjectedStuff());
        }
    }
    
    公共类无状态Actor 2:Actor,ISTATelessActor 2
    {
    专用配置的容器_容器;
    私有IRootElement_根元素;
    公共无状态Actor2()
    {
    _container=new ConfiguredContainer();/…容器在其构造函数中配置
    _rootElement=_container.Resolve();
    }
    公共异步任务DoWorkAsync()
    {
    //使用注入了所有依赖项的根元素。。
    返回wait Task.FromResult(_rootElement.WorkingWithInjectedStuff());
    }
    }
    
    我知道这很旧,但为了文档的缘故,DI现在在可靠的Actor框架中得到了支持,正如您所期望的那样

    public class ActorOne : Actor<MyActorState>, IMyActor{
    
    private readonly IDependency _dependency;
    
    public ActorOne(IDependency dependency)
    {
        _dependency = dependency;
    }}
    
    更新 现在,一切都在github和myget上:

    并与aspnet核心依赖项注入集成,无需太多麻烦,请查看readme.md的示例


    我是Unity的长期用户,并决定在使用Actor时,使用核心扩展方法来获得良好的依赖注入体验

    My program.cs现在看起来像这样:

    using (FabricRuntime fRuntime = FabricRuntime.Create()){
    
    fRuntime.RegisterActor(() => new ActorOne(new MyDependency());
    Thread.Sleep(Timeout.Infinite);}
    
    internal static class Program
    {
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                using (var container = new UnityContainer())
                {
                    container.RegisterType<IMessageProcessorClientFactory, DummyFactory>(new HierarchicalLifetimeManager());
                    container.RegisterType<IMessageClusterConfigurationStore, test>(new HierarchicalLifetimeManager());
    
                    container.WithFabricContainer();
                    container.WithActor<MessageClusterActor>();
                    container.WithActor<QueueListenerActor>();
                    container.WithStatelessFactory<ManagementApiServiceFactory>("ManagementApiServiceType");
                    container.WithActor<VmssManagerActor>();
    
                    ServiceFabricEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(ManagementApiService).Name);
    
                    Thread.Sleep(Timeout.Infinite);  // Prevents this host process from terminating to keep the service host process running.
                }
            }
            catch (Exception e)
            {
                ServiceFabricEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
    }
    
    ActorProxyTypeFactory.cs UnityFabriceExtensions.cs
    名称空间SInnovations.Azure.ServiceFabric.Unity
    {
    使用制度;
    使用系统、织物;
    使用Microsoft.Practices.Unity;
    使用Microsoft.ServiceFabric.Actors;
    使用SInnovations.Azure.ServiceFabric.Unity.Abstraction;
    使用SInnovations.Azure.ServiceFabric.Unity.Actors;
    公共静态类UnityFabriceExtensions
    {
    带有FabricContainer的公共静态IUnityContainer(此IUnityContainer容器)
    {
    返回container.WithFabricContainer(c=>FabricRuntime.Create());
    }
    带有FabricContainer的公共静态IUnityContainer(此IUnityContainer容器,Func工厂)
    {
    RegisterType(新ContainerControlledLifetimeManager(),新注入工厂(工厂));
    返回容器;
    }
    带有Actor的公共静态IUnityContainer(此IUnityContainer容器),其中TActor:ActorBase
    {
    如果(!container.IsRegistered())
    {
    RegisterType(新的层次结构CallifetimeManager());
    }
    container.RegisterType(typeof(TActor)、ActorProxyTypeFactory.CreateType()、新层次结构CallifeTimeManager());
    container.Resolve().RegisterActorFactory(()=>{
    试一试{
    var actor=container.CreateChildContainer().Resolve();
    回归演员;
    }
    捕获(例外情况除外)
    {
    投掷;
    }
    });
    返回容器;
    }
    带有StatelessFactory的公共静态IUnityContainer(此IUnityContainer容器,字符串serviceTypeName),其中TFFactory:IStatelessServiceFactory
    {
    如果(!container.IsRegistered())
    {
    RegisterType(新的ContainerControlledLifetimeManager());
    }
    container.Resolve().RegisterStatelessServiceFactory(serviceTypeName,container.Resolve());
    返回容器;
    }
    带有StatefulFactory的公共静态IUnityContainer(此IUnityContainer容器,字符串serviceTypeName),其中TFFactory:IStatefulServiceFactory
    {
    如果(!container.IsRegistered())
    {
    RegisterType(新的ContainerControlledLifetimeManager());
    }
    container.Resolve().RegisterStatefulServiceFactory(serviceTypeName,container.Resolve());
    返回容器;
    }
    带有服务的公共静态IUnityContainer(此IUnityContainer容器,字符串serviceTypeName)
    {
    container.Resolve().RegisterServiceType(serviceTypeName,typeof(TService));
    返回容器;
    }
    }
    }
    
    如果您使用的是Autofac,他们有一个特定的集成包:

    简而言之,注册是使用
    ActorRuntime.RegisterActorAsync
    /
    ServiceRuntime.RegisterServiceAsync
    执行的。然而,问题更大的部分,即对象释放,在使用动态代理的OnActivateAsync/
    OnCloseAsync
    /
    OnAbort
    覆盖中自动处理。适当寿命范围i
    public class VmssManagerActor : StatefulActor<VmssManagerActor.ActorState>, IVmssManagerActor, IRemindable
    {
        public const string CheckProvision = "CheckProvision";
    
        /// <summary>
        /// Cluster Configuration Store
        /// </summary>       
        protected IMessageClusterConfigurationStore ClusterConfigStore { get; private set; }
    
        public VmssManagerActor(IMessageClusterConfigurationStore clusterProvider)
        {
            ClusterConfigStore = clusterProvider;
        }
    
    namespace SInnovations.Azure.ServiceFabric.Unity.Abstraction
    {
        /// <summary>
        /// The <see cref="IActorDeactivationInterception"/> interface for defining an OnDeactivateInterception
        /// </summary>
        public interface IActorDeactivationInterception
        {
            void Intercept();
        }
    }
    
    namespace SInnovations.Azure.ServiceFabric.Unity.Actors
    {
        using System;
        using System.Linq;
        using System.Reflection;
        using System.Reflection.Emit;
        using SInnovations.Azure.ServiceFabric.Unity.Abstraction;
    
        public class ActorProxyTypeFactory
        {
            /// <summary>
            /// Creates a new instance of the <see cref="ActorProxyTypeFactory"/> class.
            /// </summary>
            /// <param name="target"></param>
            public ActorProxyTypeFactory(Type target)
            {
                this.target = target;
            }
    
            /// <summary>
            /// Creates the proxy registered with specific interceptor.
            /// </summary>
            /// <returns></returns>
            public static T Create<T>(IActorDeactivationInterception deactivation, params object[] args)
            {
                return (T)new ActorProxyTypeFactory(typeof(T)).Create(new object[] { deactivation }.Concat(args).ToArray());
            }
            public static Type CreateType<T>()
            {
                return new ActorProxyTypeFactory(typeof(T)).CreateType();
            }
            /// <summary>
            /// Creates the proxy registered with specific interceptor.
            /// </summary>
            /// <returns></returns>
            public object Create(object[] args)
            {
                BuidAssembly();
                BuildType();
                InterceptAllMethods();
    
                Type proxy = this.typeBuilder.CreateType();
    
                return Activator.CreateInstance(proxy, args);
            }
    
            public Type CreateType()
            {
                BuidAssembly();
                BuildType();
                InterceptAllMethods();
    
                Type proxy = this.typeBuilder.CreateType();
                return proxy;
                //  return Activator.CreateInstance(proxy, args);
            }
    
            /// <summary>
            /// Builds a dynamic assembly with <see cref="AssemblyBuilderAccess.RunAndSave"/> mode.
            /// </summary>
            /// <returns></returns>
            public void BuidAssembly()
            {
                AssemblyName assemblyName = new AssemblyName("BasicProxy");
                AssemblyBuilder createdAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                // define module
                this.moduleBuilder = createdAssembly.DefineDynamicModule(assemblyName.Name);
            }
    
            public void BuildType()
            {
                if (!target.IsPublic)
                {
                    throw new ArgumentException("Actors have to be public defined to proxy them");
                }
    
    
                this.typeBuilder =
                    this.moduleBuilder.DefineType(target.FullName + "Proxy", TypeAttributes.Class | TypeAttributes.Public, target);
                this.fldInterceptor = this.typeBuilder.DefineField("interceptor", typeof(IActorDeactivationInterception), FieldAttributes.Private);
    
                foreach (var constructor in target.GetConstructors())
                {
                    //  Type[] parameters = new Type[1];
    
                    ParameterInfo[] parameterInfos = constructor.GetParameters();
                    Type[] parameters = new Type[parameterInfos.Length + 1];
    
                    parameters[0] = typeof(IActorDeactivationInterception);
    
    
                    for (int index = 1; index <= parameterInfos.Length; index++)
                    {
                        parameters[index] = parameterInfos[index - 1].ParameterType;
                    }
    
                    ConstructorBuilder constructorBuilder =
                        typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameters);
    
                    for (int argumentIndex = 0; argumentIndex < parameters.Length; argumentIndex++)
                        constructorBuilder.DefineParameter(
                            argumentIndex + 1,
                            ParameterAttributes.None,
                            $"arg{argumentIndex}");
    
                    ILGenerator generator = constructorBuilder.GetILGenerator();
    
                    generator.Emit(OpCodes.Ldarg_0);
    
                    for (int index = 1; index < parameters.Length; index++)
                    {
                        generator.Emit(OpCodes.Ldarg, index + 1);
                    }
    
                    generator.Emit(OpCodes.Call, constructor);
    
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldarg_1);
                    generator.Emit(OpCodes.Stfld, fldInterceptor);
                    generator.Emit(OpCodes.Ret);
                }
            }
    
            /// <summary>
            /// Builds a type in the dynamic assembly, if already the type is not created.
            /// </summary>
            /// <returns></returns>
            public void InterceptAllMethods()
            {
    
                const MethodAttributes targetMethodAttributes =
                    MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
    
                var methodInfo = target.GetMethod("OnDeactivateAsync", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                {
                    if (methodInfo.IsVirtual)
                    {
                        Type[] paramTypes = GetParameterTypes(methodInfo.GetParameters());
    
                        MethodBuilder methodBuilder =
                            typeBuilder.DefineMethod(methodInfo.Name, targetMethodAttributes, methodInfo.ReturnType, paramTypes);
    
                        ILGenerator ilGenerator = methodBuilder.GetILGenerator();
    
    
                        ilGenerator.Emit(OpCodes.Ldarg_0);
                        ilGenerator.Emit(OpCodes.Ldfld, fldInterceptor);
                        ilGenerator.Emit(OpCodes.Call, typeof(IActorDeactivationInterception).GetMethod("Intercept"));
    
                        ilGenerator.Emit(OpCodes.Ldarg_0);
                        ilGenerator.Emit(OpCodes.Call, methodInfo);
                        ilGenerator.Emit(OpCodes.Ret);
    
                        return;
    
    
                    }
                }
            }
    
    
    
            private Type[] GetParameterTypes(ParameterInfo[] parameterInfos)
            {
                Type[] parameters = new Type[parameterInfos.Length];
    
                int index = 0;
    
                foreach (var parameterInfo in parameterInfos)
                {
                    parameters[index++] = parameterInfo.ParameterType;
                }
                return parameters;
            }
    
            private TypeBuilder typeBuilder;
            private ModuleBuilder moduleBuilder;
            private readonly Type target;
            private FieldInfo fldInterceptor;
    
        }
    
    }
    
    namespace SInnovations.Azure.ServiceFabric.Unity.Actors
    {
        using Microsoft.Practices.Unity;
        using SInnovations.Azure.ServiceFabric.Unity.Abstraction;
    
        public class OnActorDeactivateInterceptor : IActorDeactivationInterception
        {
            private readonly IUnityContainer container;
            public OnActorDeactivateInterceptor(IUnityContainer container)
            {
                this.container = container;
            }
    
            public void Intercept()
            {
                this.container.Dispose();
            }
        }
    }
    
    namespace SInnovations.Azure.ServiceFabric.Unity
    {
        using System;
        using System.Fabric;
        using Microsoft.Practices.Unity;
        using Microsoft.ServiceFabric.Actors;
        using SInnovations.Azure.ServiceFabric.Unity.Abstraction;
        using SInnovations.Azure.ServiceFabric.Unity.Actors;
    
        public static class UnityFabricExtensions
        {
            public static IUnityContainer WithFabricContainer(this IUnityContainer container)
            {
                return container.WithFabricContainer(c => FabricRuntime.Create());
            }
            public static IUnityContainer WithFabricContainer(this IUnityContainer container, Func<IUnityContainer,FabricRuntime> factory)
            {
                container.RegisterType<FabricRuntime>(new ContainerControlledLifetimeManager(), new InjectionFactory(factory));
                return container;
            }
    
            public static IUnityContainer WithActor<TActor>(this IUnityContainer container) where TActor : ActorBase
            {
                if (!container.IsRegistered<IActorDeactivationInterception>())
                {
                    container.RegisterType<IActorDeactivationInterception, OnActorDeactivateInterceptor>(new HierarchicalLifetimeManager());
                }
    
                container.RegisterType(typeof(TActor), ActorProxyTypeFactory.CreateType<TActor>(),new HierarchicalLifetimeManager());
                container.Resolve<FabricRuntime>().RegisterActorFactory(() => {
                    try {
                        var actor = container.CreateChildContainer().Resolve<TActor>();
                        return actor;
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    });
    
                return container;
            }
    
    
            public static IUnityContainer WithStatelessFactory<TFactory>(this IUnityContainer container, string serviceTypeName) where TFactory : IStatelessServiceFactory
            {
                if (!container.IsRegistered<TFactory>())
                {
                    container.RegisterType<TFactory>(new ContainerControlledLifetimeManager());
                }
                container.Resolve<FabricRuntime>().RegisterStatelessServiceFactory(serviceTypeName, container.Resolve<TFactory>());
                return container;
            }
            public static IUnityContainer WithStatefulFactory<TFactory>(this IUnityContainer container, string serviceTypeName) where TFactory : IStatefulServiceFactory
            {
                if (!container.IsRegistered<TFactory>())
                {
                    container.RegisterType<TFactory>(new ContainerControlledLifetimeManager());
                }
                container.Resolve<FabricRuntime>().RegisterStatefulServiceFactory(serviceTypeName, container.Resolve<TFactory>());
                return container;
            }
            public static IUnityContainer WithService<TService>(this IUnityContainer container, string serviceTypeName) 
            {
                container.Resolve<FabricRuntime>().RegisterServiceType(serviceTypeName, typeof(TService));
                return container;
            }
        }
    }