Note that there are some explanatory texts on larger screens.

plurals
  1. POC# - Instantiate a class depending on a provided interface in a generic class
    primarykey
    data
    text
    <p>I have a generic function which gets a interface as a type, now in one condition I have to create a new class depending on the interface. I have been thinking about it and a way to solve it would be to use an IoC but I was hoping there would be an other way because an IoC seems a bit like an overkill. </p> <p>below is an attempt using the visitor pattern:</p> <pre><code>public class RepositoryManager&lt;T&gt; : IRepositoryManager&lt;T&gt; where T : class, new() { public T GetOrCreate(string id) { T item = (T)CreateNew(new T(), id); return item; } } </code></pre> <p>If instead of an interface I was getting an object then I could use the visitor pattern to figure out what class to instantiate but I can't seem to figure this out depending on the interface provided.</p> <p>An other idea I had was if I can make the where declaration like an or?</p> <pre><code>public class RepositoryManager&lt;T&gt; : IRepositoryManager&lt;T&gt; where T : class, Iabc or Ixyz, new() </code></pre> <p>I hope the question is clear :)</p> <p>-Mark</p> <hr> <p>Thanks for the reply's.</p> <p>The problem is that the method can have many different interfaces assigned to it for example:</p> <p>RepositoryManager class:</p> <pre><code>private static IMedicament CreateNew(IMedicament emptyType, string id) { return new Medicament { Id = id }; } private static IRefund CreateNew(IRefund emptyType, string id) { return new Refund { Id = id }; } RepositoryManager&lt;Iabc&gt; abcRepository = new RepositoryManager&lt;Iabc&gt;(); RepositoryManager&lt;Ixyz&gt; xyzRepository = new RepositoryManager&lt;Ixyz&gt;(); Iabc abc = abcRepository.GetOrCreate("12345"); Ixyz xyz = xyzRepository.GetOrCreate("12345"); </code></pre> <p>so using <code>T item = (T)CreateNew(new T(), id);</code> won't work because I have to tell it that T can either be of type Iabc or Ixyz but when I do that I get the following error:</p> <p>The call is ambiguous between the following methods or properties: <code>RepositoryManager&lt;T&gt;.CreateNew(IMedicament, string)</code> and <code>RepositoryManager&lt;T&gt;.CreateNew(IRefund, string)</code></p> <p>It would be nice if I get this working besides just copying the code several times.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload