C# Wrapping and initializing multiple into an interface - c#

I have a api controller as below:
public class ValuesController : Controller
{
private static string dynamoDbTable = string.Empty;
private IDynamoDbClientInitialization _clientAccessor;
public ValuesController(IOptions<Dictionary<string, string>> appSettings, IDynamoDbClientInitialization clientAccessor)
{
var vals = appSettings.Value;
dynamoDbTable = vals["dynamoDbTable"];
_clientAccessor = clientAccessor;
}
[HttpGet("data")]
public async Task<List<MyData>> GetData()
{
List<ScanCondition> conditions = new List<ScanCondition>();
var response = await _clientAccessor.GetContext().ScanAsync<MyData>(conditions, AWSHelperMethods.GetDynamoDbOperationConfig(dynamoDbTable)).GetRemainingAsync();
return response.ToList();
}
}
Also I have my helper class as:
public static class AWSHelperMethods
{
public static BasicAWSCredentials SetAwsCredentials(string awsId, string awsPassword)
{
var creds = new BasicAWSCredentials(awsId, awsPassword);
return creds;
}
public static AmazonDynamoDBClient GetDynamoDbClient(BasicAWSCredentials creds, RegionEndpoint awsDynamoDbRegion)
{
var client = new AmazonDynamoDBClient(creds, awsDynamoDbRegion);
return client;
}
public static DynamoDBContext GetDynamoDbContext(AmazonDynamoDBClient client)
{
var context = new DynamoDBContext(client);
return context;
}
public static DynamoDBOperationConfig GetDynamoDbOperationConfig(string dynamoDbTable)
{
DynamoDBOperationConfig config = new DynamoDBOperationConfig() { OverrideTableName = dynamoDbTable };
return config;
}
}
My IDynamoDbClientInitialization is as:
public interface IDynamoDbClientInitialization
{
DynamoDBContext GetContext();
}
public class DynamoDbClientInitialization : IDynamoDbClientInitialization
{
private readonly DynamoDbClientSettings settings;
private DynamoDBContext _awsContext;
public DynamoDbClientInitialization(IOptions<DynamoDbClientSettings> options)
{
settings = options?.Value;
}
public DynamoDBContext GetContext()
{
//Check is context already exists. If not create a new one.
if(_awsContext != null)
{
return _awsContext;
}
else
{
var creds = AWSHelperMethods.SetAwsCredentials(settings.Id, settings.Password);
var dynamoClient = AWSHelperMethods.GetDynamoDbClient(creds, settings.Region);
_awsContext = AWSHelperMethods.GetDynamoDbContext(dynamoClient);
return _awsContext;
}
}
}
And finally my startup is as:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDynamoDbClientInitialization, DynamoDbClientInitialization>();
services.Configure<DynamoDbClientSettings>(c =>
{
c.Id = Configuration.GetValue<string>("AppSettings:awsId");
c.Password = Configuration.GetValue<string>("AppSettings:awsPassword");
c.Region = RegionEndpoint.GetBySystemName(Configuration.GetValue<string>("AppSettings:dynamoDbRegion"));
});
}
Now I created the above code without taking into consideration of Interfaces. Now I need to write unit test cases for this so wanted to know how can I create a single class and wrap up all the above
code instead of creating multiple classes like DynamoDbClientInitialization and Helper class. So that instead of initializing each and every class I just initialize a single class say "DbManager" that handles everything above.

You could use an IoC Container. (See comparison here), IoC Containers can resolve needed services automatically. Let's assume that we have interfaces IA, IB, IC and classes A, B, C implementing them:
public class A : IA
{
...
}
public class B : IB
{
private readonly IA _a;
public B(IA a)
{
_a = a;
}
...
}
public class C : IC
{
private readonly IB _b;
public C(IB b)
{
_b = b;
}
...
}
Then you would initialize the container with (the details differ between different implementations, but this gives you an idea):
public static ISomeContainer Container { get; } = container = new SomeContainer();
...
container.Register<IA, A>();
container.Register<IB, B>();
container.Register<IC, C>();
You can also specify that you want services to be created as singletons. E.g.
container.Register<IB, B>().AsSingleton();
Now you can get a service with
var myC = container.Resolve<IC>();
Now the container automatically creates an A object, then creates a B object using the first object as constructor argument. Finally, it creates and returns a C object using the B object as constructor argument.
This means that you can have different classes implementing the same interface, but having different types and numbers of constructor parameters, and the IoC resolves all these parameters automatically.
You can also register different classes for the same interface using a key that you can specify when resolving a service.

Related

Constructor dependency injection via unity with parameters from HttpContext

We're using domain to customize how our application behaves. I'll illustrate it on example:
// default behavior
public class CoreService : IService {
public virtual string Hello { get { return "Hello"; } }
public virtual string FavouriteDrink { get { return "Water"; } }
}
// german.site.com
public class GermanService : CoreService {
public override string Hello { get { return "Gutten tag"; } }
public override string FavouriteDrink { get { return "Beer"; } }
}
// usa.site.com
public class UsaService : CoreService {
public override string FavouriteDrink { get { return "Cofee"; } }
}
Services are bootstrapped as follow:
var container = new UnityContainer();
container.RegisterType<IService, CoreService>();
container.RegisterType<IService, GermanService>("german.site.com");
container.RegisterType<IService, UsaService>("usa.site.com");
I use Unity to bootstrap mvc controllers. IE:
public class HomeController : Controller {
private IService m_Service;
// contructor dependency injection magic - this resolves into "CoreService"
public HomeController([Dependency]IService service) {
if (service == null) {
throw new ArgumentNullException("service");
}
m_Service = service;
}
}
Is there a way how to change unity resolution so it'll take domain into account ? Right now I ended up with
public class HomeController : Controller {
private IService m_Service;
// contructor dependency injection magic - a lot less magical
public HomeController() {
m_Service = DomainServiceLocator.Retrieve<IService>();
}
}
Support classes:
public static class DomainServiceLocator {
private static UnityContainerAdapter adapter;
public static T Retrieve<T>() {
string domain = HttpContext.Current.Request.Url.Host;
if (adapter.IsServiceRegistered(typeof(T), domain)) {
return adapter.Resolve<T>(domain);
}
return adapter.Resolve<T>();
}
}
public class QueryableContainerExtension : UnityContainerExtension {
private List<RegisterInstanceEventArgs> registeredInstances = new List<RegisterInstanceEventArgs>();
private List<RegisterEventArgs> registeredTypes = new List<RegisterEventArgs>();
protected override void Initialize() {
this.Context.Registering += (sender, e) => { this.registeredTypes.Add(e); };
this.Context.RegisteringInstance += (sender, e) => { this.registeredInstances.Add(e); };
}
public bool IsServiceRegistered(Type service, string name) {
return registeredTypes.FirstOrDefault(e => e.TypeFrom == service && e.Name == name) != null
|| registeredInstances.FirstOrDefault(e => e.RegisteredType == service && e.Name == name) != null;
}
}
public class UnityContainerAdapter {
private readonly QueryableContainerExtension queryableContainerExtension;
private readonly IUnityContainer unityContainer;
public UnityContainerAdapter()
: this(new UnityContainer()) {
}
public UnityContainerAdapter(IUnityContainer unityContainer) {
this.unityContainer = unityContainer;
// adding extensions to unity container
this.queryableContainerExtension = new QueryableContainerExtension();
unityContainer.AddExtension(this.queryableContainerExtension);
}
public T Resolve<T>(string name) {
return unityContainer.Resolve<T>(name);
}
public T Resolve<T>() {
return unityContainer.Resolve<T>();
}
public bool IsServiceRegistered(Type service, string name) {
return this.queryableContainerExtension.IsServiceRegistered(service, name);
}
}
I like to use an injection factory in these scenarios when resolving something at runtime. Essentially you're resolving your type via the domain name:
So in your composition root you could register like this:
container.RegisterType<Func<string, IService>>
(
new InjectionFactory(c => new Func<string, IService>(name => c.Resolve<IService>(name)))
);
Then in your HomeController you can inject the delegate
public class HomeController
{
private readonly Func<string,IService> _serviceFactory;
public HomeController(Func<string, IService> serviceFactory)
{
if(serviceFactory==null)
throw new ArgumentNullException("serviceFactory");
this._serviceFactory= serviceFactory;
}
public void DoSomethingWithTheService()
{
var domain = this.HttpContext.Uri.Host;
var service = this._serviceFactory(domain);
var greeting = service.Hello;
}
}
```
This is then still unit testable and you have not leaked the DI contain implementation outside of "composition root".
Also.. should CoreService be abstract to avoid direct instantiation of it?
Below is the solution I ended up with - it is based on #Spencer idea. I've created a factory, default implementation to the factory has a reference to DI container itself (IUnityContainer in my case), so it can perform the resolution based on domain once it is asked to. It is also more "modern friendly" since in current generation of ASP.NET (ASP.NET CORE) there is no such thing as magic singleton providing current HttpContext and DI is hard coded into the framework.
public interface IFactory<T>
{
T Retrieve(string domain);
}
internal sealed class Factory<T> : IFactory<T>
{
private readonly IUnityContainer _container;
public Factory(IUnityContainer container)
{
_container = container;
}
public T Resolve(string domain)
{
// this is actually more complex - we have chain inheritance here
// for simplicity assume service is either registered for given
// domain or it throws an error
return _container.Resolve<T>(domain);
}
}
// bootstrapper
var container = new UnityContainer();
container.RegisterType<IService, CoreService>();
container.RegisterType<IService, GermanService>("german.site.com");
container.RegisterType<IService, UsaService>("usa.site.com");
container.RegisterInstance<IFactory<IService>>(new Factory<IService>(container));
And the home controller looks like
public class HomeController : Controller {
private IFactory<IService> m_Factory;
public HomeController(IFactory<IService> factory) {
m_Factory = factory;
}
private void FooBar() {
var service = m_Factory.Retrieve(this.HttpContext.Uri.Host);
var hello = service.Hello;
}
}
Its also a worth mentioning that - as I'm lazy - I've build a system of decorative attributes like
[Domain("german.site.com")]
public class GermanService : IService { ... }
[DomainRoot]
public class CoreService : IService { ... }
[Domain("usa.site.com")]
public class UsaService : CoreService { ... }
So the bootstrapping is done automatically across all types in given assembly. But that part is a bit lengthy - if anyone is interested I can post it on github.

How to export parts from an object not instantiated by the MEF container

Introduction
Class SessionModel is a service locator providing several services (I am going to elaborate my system architecture in the future, but for now I need to do it that way).
Code
I edited the following code part to be a Short, Self Contained, Correct (Compilable), Example (SSCCE):
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var sessionModel = new SessionModel(3);
// first case (see text down below):
var compositionContainer = new CompositionContainer();
// second case (see text down below):
//var typeCatalog = new TypeCatalog(typeof (SessionModel));
//var compositionContainer = new CompositionContainer(typeCatalog);
compositionContainer.ComposeExportedValue(sessionModel);
var someService = compositionContainer.GetExportedValue<ISomeService>();
someService.DoSomething();
}
}
public class SessionModel
{
private int AValue { get; set; }
[Export]
public ISomeService SomeService { get; private set; }
public SessionModel(int aValue)
{
AValue = aValue;
// of course, there is much more to do here in reality:
SomeService = new SomeService();
}
}
public interface ISomeService
{
void DoSomething();
}
public class SomeService : ISomeService
{
public void DoSomething()
{
Console.WriteLine("DoSomething called");
}
}
}
Problem
I would like MEF to consider the parts (i.e. SomeService) exported by the service locator when composing other parts, but unfortunately this does not work.
First Case
When I try to get the exported value for ISomeService there is a System.ComponentModel.Composition.ImportCardinalityMismatchException telling me there are no exports with this contract name and required type identity (ConsoleApplication1.ISomeService).
Second Case
If I create the CompositionContainer using the TypeCatalog the exception is slightly different. It is a System.ComponentModel.Composition.CompositionException telling me MEF doesn't find a way to create a ConsoleApplication1.SessionModel (which is right and the reason why I am doing it myself).
Additional Information
mefx says for both cases:
[Part] ConsoleApplication1.SessionModel from: DirectoryCatalog (Path=".")
[Export] ConsoleApplication1.SessionModel.SomeService (ContractName="ConsoleApplication1.ISomeService")
[Part] ConsoleApplication1.SessionModel from: AssemblyCatalog (Assembly="ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
[Export] ConsoleApplication1.SessionModel.SomeService (ContractName="ConsoleApplication1.ISomeService")
What do I have to do? Is this possible with MEF or do I have to use Unity or StructureMap, or something else? Can this be done implementing an ExportProvider?
OK, that's how I did it:
I implemented my own SessionModelExportProvider finding exports in my SessionModel (see code below). Class SessionModelExport is just for holding the export data and – instead of creating an instance of a service – returning the value of the property of the SessionModel.
public class SessionModelExportProvider : ExportProvider
{
private List<Export> Exports { get; set; }
public SessionModelExportProvider(SessionModel sessionModel)
{
// get all the properties of the session model having an Export attribute
var typeOfSessionModel = typeof (SessionModel);
PropertyInfo[] properties = typeOfSessionModel.GetProperties();
var propertiesHavingAnExportAttribute =
from p in properties
let exportAttributes = p.GetCustomAttributes(typeof (ExportAttribute), false)
where exportAttributes.Length > 0
select new
{
PropertyInfo = p,
ExportAttributes = exportAttributes
};
// creating Export objects for each export
var exports = new List<Export>();
foreach (var propertyHavingAnExportAttribute in propertiesHavingAnExportAttribute)
{
var propertyInfo = propertyHavingAnExportAttribute.PropertyInfo;
foreach (ExportAttribute exportAttribute in propertyHavingAnExportAttribute.ExportAttributes)
{
string contractName = exportAttribute.ContractName;
if (string.IsNullOrEmpty(contractName))
{
Type contractType = exportAttribute.ContractType ?? propertyInfo.PropertyType;
contractName = contractType.FullName;
}
var metadata = new Dictionary<string, object>
{
{CompositionConstants.ExportTypeIdentityMetadataName, contractName},
{CompositionConstants.PartCreationPolicyMetadataName, CreationPolicy.Shared}
};
var exportDefinition = new ExportDefinition(contractName, metadata);
var export = new SessionModelExport(sessionModel, propertyInfo, exportDefinition);
exports.Add(export);
}
}
Exports = exports;
}
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition,
AtomicComposition atomicComposition)
{
return Exports.Where(e => definition.IsConstraintSatisfiedBy(e.Definition));
}
}
public class SessionModelExport : Export
{
private readonly SessionModel sessionModel;
private readonly PropertyInfo propertyInfo;
private readonly ExportDefinition definition;
public SessionModelExport(SessionModel sessionModel, PropertyInfo propertyInfo, ExportDefinition definition)
{
this.sessionModel = sessionModel;
this.propertyInfo = propertyInfo;
this.definition = definition;
}
public override ExportDefinition Definition
{
get { return definition; }
}
protected override object GetExportedValueCore()
{
var value = propertyInfo.GetValue(sessionModel, null);
return value;
}
}
The problem is that the SomeService is an instance property. You could have several SessionModel objects in your system, and MEF would have no way of knowing which SessionModel is returning the ISomeService instance that is supposed to be matched to an import.
Instead, just make SessionModel a static class and SomeService a static property. Alternatively, make SessionModel a singleton. The SomeService property would still be static, but would export the service from the one-and-only instance of SessionModel.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.Reflection;
using System.Linq;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var catalogs = new AggregateCatalog();
var catalog = new System.ComponentModel.Composition.Hosting.AssemblyCatalog(Assembly.GetExecutingAssembly());
catalogs.Catalogs.Add(catalog);
var sessionModel = new SessionModel(3);
var container = new CompositionContainer(catalog);
ISomeService someService = container.GetExportedValueOrDefault<ISomeService>(sessionModel.cname);
if (someService != null)
{
someService.DoSomething();
}
}
}
public class SessionModel
{
private int AValue { get; set; }
//[Import("One",typeof(ISomeService))]
//public ISomeService SomeService { get; private set; }
public SessionModel(int aValue)
{
AValue = aValue;
// of course, there is much more to do here in reality:
}
public string cname { get { return "One"; } }
}
public class SessionModel1
{
private int AValue { get; set; }
//[Import("Two",typeof(ISomeService))]
//public ISomeService SomeService { get; private set; }
public SessionModel1(int aValue)
{
AValue = aValue;
}
public string cname { get { return "Two"; } }
}
public interface ISomeService
{
void DoSomething();
}
[Export("One",typeof(ISomeService))]
public class SomeService : ISomeService
{
public SomeService()
{
Console.WriteLine("Some Service Called");
}
public void DoSomething()
{
Console.WriteLine("DoSomething called");
Console.ReadKey();
}
}
[Export("Two",typeof(ISomeService))]
public class SomeService1 : ISomeService
{
public SomeService1()
{
Console.WriteLine("Some Service1 Called");
}
public void DoSomething()
{
Console.WriteLine("DoSomething called 1");
Console.ReadKey();
}
}
}
First case: By passing sessionModel to ComposeExportedValue you add a part of type SessionModel and not of ISomeService. To make this case work you nee to pass the service to ComposeExportedValue.
compositionContainer.ComposeExportedValue(sessionModel.SomeService);
Second case: In this case you leave the creation of parts to the container. The container can create new parts if there is either a parameter-less constructor or a constructor with parameters decorated with the ImportingConstructorAttribute. This most probably means that you will need to change your design a bit.
Personally I would go with the first case, but try to keep this to a minimum. After all the normal (and suggested) usage of MEF is letting the container create and handle parts.

Which is better practice, one client instance for the class or one in each method?

Let's say that I have a class called DataService in my client app. This class have many methods which make calls to a WCF service.
I wonder which is a better practice:
To create an instance of WebServiceClient in the class, which is initialized when an instance of the class is created, and is used by the methods, e.g:
public class DataService
{
MyWebServiceClient client = new MyWebServiceClient();
public void Method1()
{
var v = client.Operation1();
...
}
public void Method2()
{
var v = client.Operation2();
...
}
}
Or, to create and initialize an instance of WebServiceClient in each method of the class, e.g:
public class DataService
{
public void Method1()
{
var client = new MyWebServiceClient();
var v = client.Operation1();
...
}
public void Method2()
{
var client = new MyWebServiceClient();
var v = client.Operation2();
...
}
}
There is also a third option, which is to declare in class and initialize in each method:
public class DataService
{
MyWebServiceClient client;
public void Method1()
{
client = new MyWebServiceClient();
var v = client.Operation1();
...
}
public void Method2()
{
client = new MyWebServiceClient();
var v = client.Operation2();
...
}
}
When you have a dependency on another class like this, its usually a good idea to separate out its construction and pass it in (or possibly use dependency injection). This makes your DataService class easier to test, you can more easily mock your WebServiceClient this way.
consider something like...
public class DataService
{
public DataService(MyWebServiceClient client)
{
.... //Assign it to a private var...
}
}
I would use Constructor injection and one instance per class as in:
public class DataService
{
IMyWebServiceClient _client;
public DataService(IMyWebServiceClient client)
{
_client=client
}
public DataService():this(new MyWebServiceClient())
{
}
public void Method1()
{
var v = _client.Operation1();
...
}
public void Method2()
{
var v = _client.Operation2();
...
}
}
I have used method 3 most often in older applications. But recently have seen some code where you have object declaration but instantiation is done by some framework like Spring. The instance is kept inside container. Still learning about that process though.
public class DataService
{
MyWebServiceClient client;
public void Method1()
{
var v = client.Operation1();
...
}
public void Method2()
{
var v = client.Operation2();
...
}
}

How can I register class as singleton depending on optional argument in Autofac?

Let me explain my question using code, so I have a class:
public class ComplexEntity
{
private readonly ISomeDependency _someDependency;
private readonly int _optionalArg;
public ComplexEntity(ISomeDependency someDependency, int optionalArg)
{
_someDependency = someDependency;
_optionalArg = optionalArg;
}
}
and module:
public class FooModule : Module
{
protected override void OnMap(ContainerBuilder builder)
{
builder.RegisterType<ConcreteDependency>().As<ISomeDependency>().SingleInstance();
builder.RegisterType<ComplexEntity>().AsSelf();//SingleInstance fails my test below.
}
}
so my question is - how can I resolve ComplexEntity using optional argument (of type int - actually it doesn't matter what type is) and according to that optional argument it will return me same entity (if was already requested with) or create a new one - just take a look at the following test:
int optionalArgument = 10;
int anotherOptionalArgument = 11;
//I expect ResolveOptional returns same references for the same optional argument,
//thus instance1 should be equals instance2, but not equals instance3
var instance1 = _container.ResolveOptional<ComplexEntity>(
new TypedParameter(optionalArgument.GetType(), optionalArgument));
var instance2 = _container.ResolveOptional<ComplexEntity>(
new TypedParameter(optionalArgument.GetType(), optionalArgument));
var instance3 = _container.ResolveOptional<ComplexEntity>(
new TypedParameter(anotherOptionalArgument.GetType(), anotherOptionalArgument));
bool ref12Equals = object.ReferenceEquals(instance1, instance2); //should be true
bool ref13Equals = object.ReferenceEquals(instance1, instance3); //should be false
bool ref23Equals = object.ReferenceEquals(instance2, instance3); //should be false
In autofac scope can either be singleton or factory (transient), not both. If you need more complex lifetime management, I belive you need to take responsibility for that and manage that yourself. If I understood you properly, you need a scope manager that either produces new instance or returns singleton. If you still want to use DI, you can put it in container, like this:
private const int FactoryMode = 11;
private const int SingletonMode = 10;
public static void Main()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ComplexTypeScope>().SingleInstance();
containerBuilder.Register((c, p) => c.Resolve<ComplexTypeScope>().Get(p.TypedAs<int>()));
var container = containerBuilder.Build();
ComplexType instance1 = container.Resolve<ComplexType>(new TypedParameter(typeof(int), SingletonMode));
ComplexType instance2 = container.Resolve<ComplexType>(new TypedParameter(typeof(int), SingletonMode));
ComplexType instance3 = container.Resolve<ComplexType>(new TypedParameter(typeof(int), FactoryMode));
Debug.Assert(ReferenceEquals(instance1, instance2));
Debug.Assert(!ReferenceEquals(instance1, instance3));
}
class ComplexType
{
}
class ComplexTypeScope
{
private readonly Lazy<ComplexType> complexTypeSingleTon;
public ComplexTypeScope()
{
complexTypeSingleTon = new Lazy<ComplexType>(() => new ComplexType());
}
public ComplexType Get(int parameter)
{
return parameter == FactoryMode ? new ComplexType() : complexTypeSingleTon.Value;
}
}
of course with such an approach container does not manage lifetime of the components, like automatic disposal.

How to pass a parameter indirectly in Autofac

I have a dependency being injected via Func<Owned<OwnedDependency>>. One of its dependencies requires a parameter that I will only have at the point of constructing OwnedDependency.
public class OwnedDependency
{
public OwnedDependency(IDependency1 dependency)
{
}
}
public interface IDependency1
{
}
public class Dependency1 : IDependency1
{
public Dependency1(MyParameter parameter)
{
}
}
public class MyClass
{
private readonly Func<Owned<OwnedDependency>> m_ownedDependencyFactory;
public MyClass(Func<Owned<OwnedDependency>> ownedDependencyFactory)
{
m_ownedDependencyFactory = ownedDependencyFactory;
}
public void CreateOwnedDependency()
{
var parameter = new MyParameter(...);
// ** how to setup parameter with the container? **
using (var ownedDependency = m_ownedDependencyFactory())
{
}
}
}
I can't work out a clean way of setting up the instance of MyParameter.
One approach I have explored is to inject ILifetimeScope into MyClass and then do something like:
var parameter = new MyParameter(...);
using (var newScope = m_lifetimeScope.BeginLifetimeScope())
{
newScope.Resolve<IDependency1>(new TypedParameter(typeof(MyParameter), parameter));
var ownedDependency = newScope.Resolve<OwnedDependency>();
// ...
}
but the container is becoming unnecessarily intrusive. Ideally what I would like to do is inject Func<IDependency1, Owned<OwnedDependency>> and the container be willing to use parameters passed in to satisfy any necessary dependency, not just the ones on OwnedDependency.
What about doing the resolution in two steps with using another factory for IDependency1:
public class MyClass
{
private Func<MyParameter, IDependency1> dependency1Factory;
private Func<IDependency1, Owned<OwnedDependency>> ownedDependencyFactory;
public MyClass(
Func<MyParameter, IDependency1> dependency1Factory,
Func<IDependency1, Owned<OwnedDependency>> ownedDependencyFactory)
{
this.dependency1Factory = dependency1Factory;
this.ownedDependencyFactory = ownedDependencyFactory;
}
public void CreateOwnedDependency()
{
var parameter = new MyParameter();
using (var owned = ownedDependencyFactory(dependency1Factory(parameter)))
{
}
}
}

Categories

Resources