in Education by
In ASP.NET Core, one of the things you can do with Microsoft's dependency injection framework is bind "open generics" (generic types unbound to a concrete type) like so: public void ConfigureServices(IServiceCollection services) { services.AddSingleton(typeof(IRepository<>), typeof(Repository<>)) } You can also employ the factory pattern to hydrate dependencies. Here's a contrived example: public interface IFactory { T Provide(); } public void ConfigureServices(IServiceCollection services) { services.AddTransient(typeof(IFactory<>), typeof(Factory<>)); services.AddSingleton( typeof(IRepository), p => p.GetRequiredService>().Provide() ); } However, I have not been able to figure out how to combine the two concepts together. It seems like it would start with something like this, but I need the concrete type that is being used to hydrate an instance of IRepository<>. public void ConfigureServices(IServiceCollection services) { services.AddTransient(typeof(IFactory<>), typeof(Factory<>)); services.AddSingleton( typeof(IRepository<>), provider => { // Say the IServiceProvider is trying to hydrate // IRepository when this lambda is invoked. // In that case, I need access to a System.Type // object which is IRepository. // i.e.: repositoryType = typeof(IRepository); // If I had that, I could snag the generic argument // from IRepository and hydrate the factory, like so: var modelType = repositoryType.GetGenericArguments()[0]; var factoryType = typeof(IFactory>).MakeGenericType(modelType); var factory = (IFactory)p.GetRequiredService(factoryType); return factory.Provide(); } ); } If I try to use the Func functor with an open generic, I get this ArgumentException with the message Open generic service type 'IRepository' requires registering an open generic implementation type. from the dotnet CLI. It doesn't even get to the lambda. Is this type of binding possible with Microsoft's dependency injection framework? JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
The net.core dependency does not allow you to provide a factory method when registering an open generic type, but you can work around this by providing a type that will implement the requested interface, but internally it will act as a factory. A factory in disguise: services.AddSingleton(typeof(IMongoCollection<>), typeof(MongoCollectionFactory<>)); //this is the important part services.AddSingleton(typeof(IRepository<>), typeof(Repository<>)) public class Repository : IRepository { private readonly IMongoCollection _collection; public Repository(IMongoCollection collection) { _collection = collection; } // .. rest of the implementation } //and this is important as well public class MongoCollectionFactory : IMongoCollection { private readonly _collection; public RepositoryFactoryAdapter(IMongoDatabase database) { // do the factory work here _collection = database.GetCollection(typeof(T).Name.ToLowerInvariant()) } public T Find(string id) { return collection.Find(id); } // ... etc. all the remaining members of the IMongoCollection, // you can generate this easily with ReSharper, by running // delegate implementation to a new field refactoring } When the container resolves the MongoCollectionFactory it will know what type T is and will create the collection correctly. Then we take that created collection save it internally, and delegate all calls to it. ( We are mimicking this=factory.Create() which is not allowed in csharp. :)) Update: As pointed out by Kristian Hellang the same pattern is used by ASP.NET Logging public class Logger : ILogger { private readonly ILogger _logger; public Logger(ILoggerFactory factory) { _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T))); } void ILogger.Log(...) { _logger.Log(logLevel, eventId, state, exception, formatter); } } original discussion here: https://twitter.com/khellang/status/839120286222012416

Related questions

0 votes
    What is the benefit of Factory pattern?...
asked Nov 7, 2020 in Education by Editorial Staff
0 votes
    What is Abstract Factory pattern?...
asked Nov 7, 2020 in Education by Editorial Staff
0 votes
    What is Factory pattern?...
asked Nov 7, 2020 in Education by Editorial Staff
0 votes
    Given the widely-shared type Omit, with the definition: type Omit = Pick; which is used to subtract ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 29, 2022 in Education by JackTerrance
0 votes
    What is the default date pattern in Talend Open Studio? MM-DD-YY DD-MM-YY DD-MM-YYYY YY-MM-DD...
asked Mar 24, 2021 in Technology by JackTerrance
0 votes
    Why are generics used? (a) Generics make code more fast (b) Generics make code more optimised and readable (c) ... & Packages of Java Select the correct answer from above options...
asked Feb 23, 2022 in Education by JackTerrance
0 votes
    Which of the following is an incorrect statement regarding the use of generics and parameterized types in Java? (a ... Packages of Java Select the correct answer from above options...
asked Feb 23, 2022 in Education by JackTerrance
0 votes
    Why are generics used? (a) Generics make code more fast (b) Generics make code more optimised and ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Oct 24, 2021 in Education by JackTerrance
0 votes
    i have an Angular Factory that gets a single date from the backend of my spring application, and i ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 7, 2022 in Education by JackTerrance
0 votes
    I've a lookup activity with gets value from a container within a blob. I have a foreach activity which is ... : data.speed> 500 Select the correct answer from above options...
asked Feb 4, 2022 in Education by JackTerrance
0 votes
    I have a HDInsight Hadoop cluster (Linux, deployed separately) on Azure VNet (restricting client IPs using NSG). ... Data Factory? Select the correct answer from above options...
asked Feb 2, 2022 in Education by JackTerrance
0 votes
    A factory has two machines A and B. Past record shows that machine A produced 60% of the items of output and ... produced by machine B? Select the correct answer from above options...
asked Nov 25, 2021 in Education by JackTerrance
0 votes
    The probability that a bulb produced by a factory will fuse after 150 days of use is 0.05. Find the probability ... 150 days of use Select the correct answer from above options...
asked Nov 25, 2021 in Education by JackTerrance
0 votes
    In a bulb factory, three machines, A, B, C, manufacture 60%, 25% and 15% of the total production respectively ... by machine C. Select the correct answer from above options...
asked Nov 22, 2021 in Education by JackTerrance
...