2017-01-30 234 views
-1

.Net使用反射的核心Dependenct注入。我可以做下面的事情吗?.Net Core Startup.cs(无第三方容器)使用反射的依赖注入

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

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

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; 

     } 
    } 

回答

0

而不是

services.AddScoped(ICandidateService)(candidateService); 

services.AddSingletone<ICandidateService>(candidateService); 
如果你想只有一个预创建的实例

或制作工厂Func键,如果你需要Scoped一生:

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

我在候选服务下得到swiggley reg行,错误是。参数2:无法从ICandidateService转换为'System.Func ' – Sridev

+0

好,现在我们有具体的错误:)现在,主要问题是 - 你想有'Scoped'服务(为什么你注册预先创建的实例总是一样?)还是'Singleton'? – Dmitry

+0

根据FactoryModel(上面的代码),我在那里硬编码(实际上来自appsettings.json),并根据存储库类型连接到不同的ICustomerService实例。是的,你是对的,我想我可以做Singleton。 – Sridev