Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6552643
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T12:29:06+00:00 2026-05-25T12:29:06+00:00

I’m struggling with implementing a factory object. Here’s the context : I’ve in a

  • 0

I’m struggling with implementing a factory object. Here’s the context :

I’ve in a project a custom store. In order to read/write records, I’ve written this code in a POCO model/separated repository:

public class Id { /* skip for clarity*/} // My custom ID representation

public interface IId
{
    Id Id { get; set; }
}
public interface IGenericRepository<T> where T : IId
{
    T Get(Id objectID);
    void Save(T @object);
}
public interface IContext
{
    TRepository GetRepository<T, TRepository>() 
        where TRepository : IGenericRepository<T> 
        where T:IId;
    IGenericRepository<T> GetRepository<T>() 
        where T:IId;
}

My IContext interface defines two kind of repositories.
The former is for standard objects with only get/save methods, the later allows me to define specifics methods for specific kind of objects. For example :

public interface IWebServiceLogRepository : IGenericRepository<WebServiceLog>
{
    ICollection<WebServiceLog> GetOpenLogs(Id objectID);
}

And it the consuming code I can do one of this :

  • MyContext.GetRepository<Customer>().Get(myID); –> standard get
  • MyContext.GetRepository<WebServiceLog, IWebServiceLogRepository>().GetOpenLogs(myID); –> specific operation

Because most of objects repository are limited to get and save operations, I’ve written a generic repository :

public class BaseRepository<T> : IGenericRepository<T>
    where T : IId, new()
{
    public virtual T Get(Id objectID){ /* provider specific */ }
    public void Save(T @object) { /* provider specific */ }
}

and, for custom ones, I simply inherits the base repository :

internal class WebServiceLogRepository: BaseRepository<WebServiceLog>, IWebServiceLogRepository
{
    public ICollection<WebServiceLog> GetByOpenLogsByRecordID(Id objectID)
    {
        /* provider specific */
    }
}

Everything above is ok (at least I think it’s ok). I’m now struggling to implement the MyContext class. I’m using MEF in my project for other purposes. But because MEF doesn’t support (yet) generic exports, I did not find a way to reach my goal.

My context class is looking like by now :

[Export(typeof(IContext))]
public class UpdateContext : IContext
{
    private System.Collections.Generic.Dictionary<Type, object> m_Implementations;

    public UpdateContext()
    {
        m_Implementations = new System.Collections.Generic.Dictionary<Type, object>();
    }
    public TRepository GetRepository<T, TRepository>()
        where T : IId
        where TRepository : IGenericRepository<T>
    {
        var tType = typeof(T);
        if (!m_Implementations.ContainsKey(tType))
        {
            /* this code is neither working nor elegant for me */
            var resultType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(
                (a) => a.GetTypes()
                ).Where((t)=>t.GetInterfaces().Contains(typeof(TRepository))).Single();

            var result = (TRepository)resultType.InvokeMember("new", System.Reflection.BindingFlags.CreateInstance, null, null, new object[] { this });

            m_Implementations.Add(tType, result);
        }
        return (TRepository)m_Implementations[tType];
    }

    public IGenericRepository<T> GetRepository<T>() where T : IId
    {
        return GetRepository<T, IGenericRepository<T>>();
    }
}

I’d appreciate a bit of help to unpuzzle my mind with this quite common scenario

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T12:29:06+00:00Added an answer on May 25, 2026 at 12:29 pm

    Not sure if I’ve understood you correctly, but I think you’re perhaps over complicating things. To begin with, make sure you’ve designed your code independent of any factory or Dependency Injection framework or composition framework.

    For starters lets look at what you want your calling code to look like, this is what you said:

    MyContext.GetRepository<Customer>().Get(myID); --> standard get
    MyContext.GetRepository<WebServiceLog, IWebServiceLogRepository>().GetOpenLogs(myID);
    

    You don’t have to agree with my naming choices below, but it indicates what I undertand from your code, you can tell me if I’m wrong. Now, I feel like the calling would be simpler like this:

    RepositoryFactory.New<IRepository<Customer>>().Get(myId);
    RepositoryFactory.New<IWebServiceLogRepository>().GetOpenLogs(myId);
    

    Line 1:
    Because the type here is IRepository it’s clear what the return type is, and what the T type is for the base IRepository.

    Line 2:
    The return type here from the factory is IWebServiceLogRepository. Here you don’y need to specify the entity type, your interface logically already implements IRepository. There’s no need to specify this again.

    So your interface for these would look like this:

    public interface IRepository<T>
    {
    T Get(object Id);
    T Save(T object);
    }
    
    public interface IWebServiceLogRepository: IRepository<WebServiceLog>
    {
    List<WebServiceLog> GetOpenLogs(object Id);
    }
    

    Now I think the implementations and factory code for this would be simpler as the factory only has to know about a single type. On line 1 the type is IRepository, and in line 2, IWebServiceLogRepository.

    Try that, and try rewriting your code to simply find classes that implement those types and instantiating them.

    Lastly, in terms of MEF, you could carry on using that, but Castle Windsor would really make things much simpler for you, as it lets you concentrate on your architecture and code design, and its very very simple to use. You only ever reference Castle in your app startup code. The rest of your code is simply designed using the Dependency Injection pattern, which is framework agnostic.

    If some of this isn’t clear, let me know if you’d like me to update this answer with the implementation code of your repositories too.

    UPDATE

    and here’s the code which resolves the implementations. You were making it a bit harder for yourself by not using the Activator class.

    If you use Activator and use only one Generic parameter as I’ve done in the method below, you should be ok. Note the code’s a bit rough but you get the idea:

    public static T GetThing<T>()
            {
                List<Type> assemblyTypes = AppDomain.CurrentDomain.GetAssemblies()
                                            .SelectMany(s => s.GetTypes()).ToList();
    
                Type interfaceType = typeof(T);
    
                if(interfaceType.IsGenericType)
                {
                    var gens = interfaceType.GetGenericArguments();
                    List<Type> narrowed = assemblyTypes.Where(p => p.IsGenericType && !p.IsInterface).ToList();
                    var implementations = new List<Type>();
                    narrowed.ForEach(t=>
                    {
                        try
                        {
                            var imp = t.MakeGenericType(gens);
                            if(interfaceType.IsAssignableFrom(imp))
                            {
                                implementations.Add(imp);     
                            }  
                        }catch
                        {
                        }
                    });
    
                    return (T)Activator.CreateInstance(implementations.First());
                }
                else
                {
                    List<Type> implementations = assemblyTypes.Where(p => interfaceType.IsAssignableFrom(p) && !p.IsInterface).ToList();
    
                    return (T)Activator.CreateInstance(implementations.First());
                }
    
            }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
i got an object with contents of html markup in it, for example: string
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.