title: Is it possible to create a generic factory with constructor with parameters using Activator.CreateInstance()?
body: <p>Is there any way to achieve a generic factory when the class it returns requires a parameter in the constructor? All my factories look like this:</p>
  
  <pre><code>public static class UserServiceFactory
  {
      public static UserService GetService()
      {
          UserRepository userRepository = new UserRepository();
          return new UserService(userRepository);
      }
  
  }
  </code></pre>
  
  <p>I tried something like this:</p>
  
  <pre><code> public static TServiceClass GetService&lt;TServiceClass&gt;()
          where TServiceClass : class, new()
      {
          TServiceClass serviceClass = null;
  
          string repositoryName = typeof (TServiceClass).ToString().Replace("Service", "Repository");
          Type type = Type.GetType(repositoryName);
  
          if (type != null)
          {
              object repository = Activator.CreateInstance(type);
              serviceClass =  (TServiceClass)Activator.CreateInstance(typeof (TServiceClass), new[]{repository});
          }
  
          return serviceClass;
      }
  </code></pre>
  
  <p>However, this of course won't work because I can't use a class that has no parameterless constructor as a generic parameter, but I feel like I am close. I thought about passing the Service class like <code>GetService(Type serviceClassType)</code> but then I can't declare the method's return type and would have to cast it when I call it, which I want to avoid.</p>
  
  <p>Is there another approach? Is this even possible?</p>