.Net Core Startup.cs(无第三方容器)使用反射的依赖注入

时间:2017-01-30 11:48:54

标签: .net asp.net-core dependencies

.Net Core Dependenct Injection使用Reflection。我可以做下面的事吗。

错误:显示Visual Stuido设计师 ICandidateService是类型,在给定的上下文中无效。

请建议,我们可以使用第三方容器来做到这一点。

    public void ConfigureServices(IServiceCollection services)
            { 
               var candidateService = ServiceInstance.GetService<ICandidateService>(
                    new FactoryModel()
                    {
                        Connection = "User ID=postgres;Password=123;Host=localhost;Port=5432;Database=Test12;Pooling=true;",
                        DLLCulture = "Culture=neutral",
                        DLLRef = "EF.Service.SQL",
                        DLLVer = "Version=1.0.0.0",
                        ServiceType = ServiceTypes.PostgreSQL
                    }
                );


               services.AddScoped(ICandidateService)(candidateService);


    }


//Service Instance Class
public static class ServiceInstance
    { 
        public static T GetService<T>(FactoryModel factoryModel)
        {
            if (string.IsNullOrEmpty(factoryModel.Connection) || string.IsNullOrEmpty(factoryModel.DLLRef) ||
                string.IsNullOrEmpty(factoryModel.DLLVer) || string.IsNullOrEmpty(factoryModel.DLLCulture))
                throw new NullReferenceException("Missing dataType or connection string");

            return GetSQLServiceIntance<T>(factoryModel);
        }

        public static T GetSQLServiceIntance<T>(FactoryModel factoryModel)
        { 
            Type responseContract = GetSQLServiceType<T>(factoryModel);

            object serviceInstance = Activator.CreateInstance(responseContract, factoryModel.Connection, factoryModel.ServiceType.ToString());
            T thisService = (T)serviceInstance;
            return thisService;

        }

        public static Type GetSQLServiceType<T>(FactoryModel factoryModel)
        {
            var requestContract = typeof(T).Name.Remove(0, 1);
            string typeName = $"{factoryModel.DLLRef}.{requestContract}, {factoryModel.DLLRef}, {factoryModel.DLLVer}, {factoryModel.DLLCulture}";

            Type responseContract = Type.GetType(typeName);

            return  responseContract;

        }
    }

1 个答案:

答案 0 :(得分:0)

而不是

services.AddScoped(ICandidateService)(candidateService);

services.AddSingletone<ICandidateService>(candidateService);

如果您只想拥有一个预先创建的实例,

如果您需要Scoped生命周期,请制作工厂-Func:

services.AddScoped<ICandidateService>(_ => ServiceInstance.GetService<ICandidateService>(new FactoryModel() {...}));