How to safely dispose CCR Dispatcher, DispatcherQueue and Interleave - ccr

I am trying to find the best way to dispose the CCR Dispatcher, DispatcherQueue and Interleave which are interlinked to each other. I have a class say "MyClass" that has a single dispatcher and a single dispatcher queue. The class exposes a single PortSet to which clients can post messages to. In "MyClass", I have created persistent receivers for those messages and attached to the dispatcher queue. I have also added all the receivers as part of a single Interleave. Now when the client thinks it is done using "MyClass" class, I want the client to destroy the class safely. There are three things that needs to destroy here which are the dispatcher, the dispatcher queue and the interleave. What is the best way to do that? I happened to read the discussions in the link http://channel9.msdn.com/shows/Going+Deep/CCR-Programming-Jeffrey-Richter-and-George-Chrysanthakopoulos/. Although, not mentioned explicitly, I inferred that the right way to Dispose is that I need to first post a tear down message to the interleave, wait for the interleave to teardown then dispose the dispatcher queue. Now, the dispose code of my class will look like the following.
var teardownInterleave = new TeardownInterleave();
InternalMessagesPort.PostUnknownType(teardownInterleave);
var done = new ManualResetEvent(false);
Activate(Arbiter.Receive(false, teardownInterleave.CompletionPort,
emptyValue => done.Set()));
done.WaitOne();
Thread.Sleep(100);
// Dispose the TaskQ
TaskQueue.Dispose();
/// <summary>
/// Message posted to any interleave asking it to teardown.
/// </summary>
public sealed class TeardownInterleave
{
/// <summary>
/// Gets the completion port.
/// </summary>
/// <value>
/// The completion port.
/// </value>
public Port<EmptyValue> CompletionPort { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TeardownInterleave" /> class.
/// </summary>
public TeardownInterleave()
{
CompletionPort = new Port<EmptyValue>();
}
}
Please clarify if this is the right approach or am I missing something.
Thanks,
Venkat

Minor Note: On InternalMessagesPort you shouldn't need to use PostUnknownType, you should just be able to use Post()
The only thing that you should need to dispose is the Dispatcher, everything else should take care of itself through garbage collection.
In general CCR objects (ports, tasks, receivers, causalities etc.) work well with GC. In simple terms, as soon as there are no references to a port then everything else that is associated with it will be collected also (assuming no other references of course).
DispatcherQueues are cleaned up when the owning Dispatcher is disposed.

Related

what does a specific method do in this open source solution

Recently I'm trying to understand how NopCommerce plugins work.
I'll try to make my question as clear as possible and making sense for you without having the solution opened on your computer.
In nopCommerce plugins everything start with having a class which must have the definition for IWidgetPlugin interface and being derived from BasePlugin.
In one of the predefined plugins there is a class called NivoSliderPlugin and this class overrides some of it's base class methods and has the definition for IWidgetPlugin's methods.
here is the code:
public class NivoSliderPlugin : BasePlugin, IWidgetPlugin
{
// Here there are some fields that are referencing to different interfaces and then
they're injected to the class throw it's constructor
// This method gets a configuration page URL
public override string GetConfigurationPageUrl()
{
return _webHelper.GetStoreLocation() + "Admin/WidgetsNivoSlider/Configure";
}
}
In the above code I only mentioned the part of the code that I have a question about.
_webHelper is a reference to an interface and accept the incoming parameter of type bool.
Regardless the second part of the return, I mean the URL path which is "Admin/WidgetsNivoSlider/Configure", I'm wondering how _webHelper.GetStoreLocation() works ?
As you know _webHelper.GetStoreLocation() has no definition !
I hope what I just asked makes sense.
If it's not clear please let me know to make it clearer.
I'll appreciate it.
Let's start with IWidgetPlugin. This interface is not required to implement for all plugins in NopCommerce. This is required when you are developing a Widget type plugin. Here Nivo Slider is a widget type plugin, that's why it implemented IWidgetPlugin interface. Here is the implementation for Nivo slider.
/// <summary>
/// Gets a value indicating whether to hide this plugin on the widget list page in the admin area
/// </summary>
public bool HideInWidgetList => false;
/// <summary>
/// Gets a name of a view component for displaying widget
/// </summary>
/// <param name="widgetZone">Name of the widget zone</param>
/// <returns>View component name</returns>
public string GetWidgetViewComponentName(string widgetZone)
{
return "WidgetsNivoSlider";
}
/// <summary>
/// Gets widget zones where this widget should be rendered
/// </summary>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the widget zones
/// </returns>
public Task<IList<string>> GetWidgetZonesAsync()
{
return Task.FromResult<IList<string>>(new List<string> { PublicWidgetZones.HomepageTop });
}
If you want to develop a payment plugin, then you have to implement IPaymentMethod (i.e. PayPal, Stripe, Cash on Delivery) and IShippingRateComputationMethod for shipping methods (i.e. UPS, USPS). Also there are many other types of plugins available in nopCommerce. See the list below.
BasePlugin is an abstract class, which is required to be inherited for all plugin class. It has a virtual method named GetConfigurationPageUrl() which returns null by default. But this virtual method can be overridden from each plugin class and can return admin side configuration url for that plugin. Here is the overridden method for Nivo slider plugin.
/// <summary>
/// Gets a configuration page URL
/// </summary>
public override string GetConfigurationPageUrl()
{
return _webHelper.GetStoreLocation() + "Admin/WidgetsNivoSlider/Configure";
}
Here _webHelper.GetStoreLocation() is a method which returns base url of the site. This method is implemented in Nop.Core.WebHelper class. The optional boolean parameter (useSsl) for this method is used whether to consider https:// or not for the site base url. If this method is overridden from a specific plugin, then a Configure button will be displayed in local plugin list page.

Safely re-initialize "single instance" dependency in a DI Container

I have a widely used cache interface in a web application with the implementation currently registered as SingleInstance.
This current cache implementation assumes single threaded initialization, but once initialized is immutable, so is safely shared across multiple threads.
However, this means that currently, if the underlying values change, the cache doesn't get updated until the application is restarted. While updating the underlying values is rare, we would now like to provide application behavior that modifies the underlying values, and then tells the cache to refresh.
I could modify the cache implementation to use locking, or perhaps utilize one of the .NET concurrent collections to safely update the cache values.
However, I'm wondering if autofac provides a capability that would allow me to change out the registered instance for a new instance on the next request, so that the cache implementation itself would not need to be modified.
So the ideal behavior would be, that when we modify the underlying values, we trigger the creation of a new cache instance. Once the instance is finished initializing, all in-progress requests continue with the old cache instance, any new http request scopes resolve to the updated instance.
Does autofac provide a built-in way to support this scenario?
You can never safely replace a singleton registered instance in your container. Once other singleton components depend on that, they will simply hold a reference to the old instance, and replacing the instance in the container means that some components (that will be created after the replace action) will refer to the new instance, while other components keep referring to the old instance. This will hardly ever lead to the behavior you like, and will most likely cause bugs.
My advice is never try to change your container's registrations, once the application is running. This will very quickly become quite complex to oversee whether the situation is correct and is thread-safe. For instance, what if you replace the instance at the time that the object graph for another thread is being resolved? It could mean that that object graph holds both a reference to the old and the new instance.
Instead, solve this problem at the application level. First of all, you need two APIs; one for reading the cache, and a second for updating the cache. Both can be implemented using the same component though:
// Very simplified version of what you actually might need
interface ICache { CacheObject Get(); }
interface ICacheUpdater { void Set(CacheObject o); }
A simplistic implementation could look like this:
sealed class Cache : ICache, ICacheUpdater
{
private static CacheObject instance;
public void Set(CacheObject o) => instance = o;
public CacheObject Get() => instance;
}
This implementation might work, but if the cache is retrieved multiple times within the same request, it's possible to read both the old and the new values within the same request (since a different thread can call Set in between). This might be a problem. In that case, you can change the implementation to the following:
sealed class HttpCache : ICache, ICacheUpdater
{
private static readonly object key = typeof(HttpCache);
private static CacheObject instance;
private static IDictionary items => HttpContext.Current.Items;
public void Set(CacheObject o) => instance = o;
public CacheObject Get() => (CacheObject)items[key] ?? (items[key] = instance);
}
In this implementation an extra reference to the cache object is stored in the HttpContext.Items dictionary. This ensures that during the execution of a single (web) request, always the same instance is retrieved.
This example assumes you are running a web application, but you can easily imagine a solution for a different application type.
To update a component registered as a single instance, you can have a registration like this :
builder.RegisterType<ServiceProvider>().SingleInstance();
builder.Register(c => c.Resolve<ServiceProvider>().Service).As<IService>();
and ServiceProvider like this :
public class ServiceProvider
{
public ServiceProvider()
{
this.Service = new Service();
}
public IService Service { get; set; }
}
To update the instance you only have to do that :
container.Resolve<ServiceProvider>().Service = newInstance;
The second part of the question may be more difficult :
Once the instance is finished initializing, all in-progress requests continue with the old cache instance, any new http request scopes resolve to the updated instance.
What you want is to inject a single instance registration in a specific scope. To make this, you can use the ChildLifetimeScopeBeginning event to set the instance for the whole life of scope.
builder.RegisterType<ServiceProvider>().Named<ServiceProvider>("root").SingleInstance();
builder.RegisterType<ServiceProvider>().InstancePerRequest();
builder.Register(c => c.Resolve<ServiceProvider>().Service).As<IService>();
IContainer container = builder.Build();
container.ChildLifetimeScopeBeginning += (sender, e) =>
{
ServiceProvider scopeServiceProvider = e.LifetimeScope.Resolve<ServiceProvider>();
ServiceProvider rootServiceProvider = container.ResolveNamed<ServiceProvider>("root");
scopeServiceProvider.Service = rootServiceProvider.Service;
};
To change the global IService instance you will have to resolve the "root" named ServiceProvider
scope.ResolveNamed<ServiceProvider>("root").Service = newInstance;
and to change the scope only IService instance you will resolve a normal ServiceProvider
scope.Resolve<ServiceProvider>().Service = newInstance;

MVC DisplayNameAttribute and Ninject: Possible?

Let's assume following basic Project-Setup:
- Core
-- Attributes
--- CustomDisplayNameAttribute : DisplayNameAttribute
- UI
UI represents the MVC Web interface, the core implements all the domain business objects, including self written attributes like CustomDisplayNameAttribute. This attribute contains additional dependencies like a language resolver, which e.g. deals with fallback orders. Hibernate sessions would be another possible dependency.
In earlier projects, these attributes did a global request in order to get the resolver. This is IMO ugly and should be handled differently. Furthermore, Core should stay without HttpContext: since the language-resolver is required per request, it might end up in HttpContext Items Collection.
Now I am quite a beginner with Ninject, and I am not sure if it is the right tool in order to get such dependencies into something like a CustomDisplayNameAttribute?
In words it would be something like this:
If the attribute is created, populate the additional language resolver property with the language resolver from HttpContext Items Collection
If there is no HttpContext (e.g. testing, quartz jobs etc.), get it from somewhere else.
Thx for any inputs
Edit: Sample-Code
namespace Core.Attributes
{
public class CustomDisplayNameAttribute : DisplayNameAttribute
{
private string textCode;
/// <param name="textCode">According to this Text-Code, we will load
/// and resolve the text.</param>
public DeimosDisplayNameAttribute(string textCode)
{
this.textCode = textCode;
}
/// <summary>
/// Load and resolve Text according to Text-Code
/// </summary>
public override string DisplayName
{
get
{
// Load - Ooops: First global access
// --> How can it be injected with IoC?
TextbausteinRepository repo = Root.GetTextBausteinRepository();
var textItem = repo.GetText(textCode);
// Resolve - Ooops: Second global access
// --> How can it be injected with IoC?
TextResolver resolver = Root.GetTextResolver();
return resolver.resolve(textItem);
}
}
}
}
Edit 2: In that context, it seems that there is no way around a global access, like a registry pattern or similar. UI would register the needed data in there, and the attributes would access it from there. We started to think about storing it in ThreadLocal<T>, but this seems not really save due to the fact that there is a possibility of thread-swapping during the life-cycle. So there seems no way around storing HttpContext in the registry layer. For more info about this subject, see [Cup(Of T)][1].
I don't think this is possible, because data attributes are not run-time dispatched like filters are. As such, there's no place to intercept the creation and inject what you're looking for.

Singletons and ASP.NET MVC

Right now I'm having an issue with a Singleton that I just wrote for use in ASP.NET MVC -- My Singleton looks like this:
public sealed class RequestGenerator : IRequestGenerator
{
// Singleton pattern
private RequestGenerator()
{
requestList = new Stack<Request>();
appSettings = new WebAppSettings();
}
private static volatile RequestGenerator instance = new RequestGenerator();
private static Stack<Request> requestList = new Stack<Request>();
// abstraction layer for accessing web.config
private static IAppSettings appSettings = new WebAppSettings();
// used for "lock"-ing to prevent race conditions
private static object syncRoot = new object();
// public accessor for singleton
public static IRequestGenerator Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new RequestGenerator();
}
}
}
return instance;
}
}
private const string REQUESTID = "RequestID";
// Find functions
private Request FindRequest(string component, string requestId)
private List<Request> FindAllRequests(string component, string requestId)
#region Public Methods required by Interface
// Gets and increments last Request ID from Web.Config, creates new Request, and returns RequestID
public string GetID(string component, string userId)
// Changes state of Request to "submitted"
public void SetID(string component, string requestId)
// Changes state of Request to "success" or "failure" and records result for later output
public void CloseID(string component, string requestId, bool success, string result)
// Verifies that Component has generated a Request of this ID
public bool VerifyID(string component, string requestId)
// Verifies that Component has generated a Request of this ID and is owned by specified UserId
public bool VerifyID(string component, string userId, string requestId)
// Returns State of Request ID (Open, Submitted, etc.)
public Status GetState(string component, string requestId)
// Returns Result String of Success or Failure.
public string GetResult(string component, string requestId)
#endregion
}
And my controller code looks like this:
public ViewResult SomeAction()
{
private IRequestGenerator reqGen = RequestGenerator.Instance;
string requestId = reqGen.GetID(someComponentName, someUserId);
return View(requestId);
}
Everything works okay the first time I hit the controller. "reqGen" is assigned the instance of the Singleton. A new instance of Request is added to the internal list of the Singleton. And then we return a View(). The next time I hit this controller's SomeAction(), I'm expecting the Singleton to contain the List with the instance of SomeClass that I had just added, but instead the List is empty.
What's happened? Has Garbage Collection gobbled up my object? Is there something special I need to consider when implementing the Singleton pattern in ASP.NET MVC?
Thanks!
EDIT: Ahh, the lightbulb just went on. So each new page request takes place in a completely new process! Got it. (my background is in desktop application development, so this is a different paradigm for me...)
EDIT2: Sure, here's some more clarification. My application needed a request number system where something being requested needed a unique ID, but I had no DB available. But it had to be available to every user to log the state of each request. I also realized that it could double as a way to regulate the session, say, if a use double-clicked the request button. A singleton seemed like the way to go, but realizing that each request is in its own process basically eliminates the singleton. And I guess that also eliminates the static class, right?
EDIT3: ok, I've added the actual code that I'm working with (minus the implementation of each Method, for simplicity sake...) I hope this is clearer.
EDIT4: I'm awarding the green check mark to Chris as I'm beginning to realize that an application-level singleton is just like having a Global (and global's are evil, right?) -- All kidding aside, the best option really is to have a DB and SQLite seems like the best fit for now, although I can definitely see myself moving to an Oracle instance in the future. Unfortunately, the best option then would be to use an ORM, but that's another learning curve to climb. bugger.
EDIT5: Last edit, I swear. :-)
So I tried using HttpRuntime.Cache, but was surprised to find that my cache was getting flushed/invalidated constantly and couldn't figure out what was going on. Well, I was getting tripped up by a side-effect of something else I was doing: Writing to "Web.config"
The Answer --> Unbeknownst to me, when "web.config" is altered in anyway, the application is RESTARTED! Yup, everything gets thrown away. My singleton, my cache, everything. Gah. No wonder nothing was working right. Looks like writing back to web.config is generally bad practice which I shall now eschew.
Thanks again to everyone who helped me out with this quandary.
The singleton is specific to the processing instance. A new instance is being generated for each page request. Page requests are generally considered stateless so data from one doesn't just stick around for another.
In order to get this to work at the application level, the instance variable will have to be declared there. See this question for a hint on how to create an application level variable. Note that this would make it available across all requests.. which isn't always what you want.
Of course, if you are trying to implement some type of session state then you might just use session or use some type of caching procedure.
UPDATE
Based on your edits: A static class should not maintain data. It's purpose is to simply group some common methods together, but it shouldn't store data between method calls. A singleton is an altogether different thing in that it is a class that you only want one object to be created for the request.
Neither of those seem to be what you want.
Now, having an application level singleton would be available to the entire application, but that crosses requests and would have to be coded accordingly.
It almost sounds like you are trying to build an in memory data store. You could go down the path of utilizing one of the various caching mechanisms like .NET Page.Cache, MemCache, or Enterprise Library's Caching Application Block.
However, all of those have the problem of getting cleared in the event the worker process hosting the application gets recycled.. Which can happen at the worst times.. And will happen based on random things like memory usage, some timer expired, a certain number of page recompiles, etc.
Instead, I'd highly recommend using some type of persisted storage. Whether that be just xml files that you read/write from or embedding something like SQL Lite into the application. SQL Lite is a very lightweight database that doesn't require installation on the server; you just need the assemblies.
You can use Dependency Injection to control the life of the class. Here's the line you could add in your web.config if you were using Castle Windsor.
<component id="MySingleton" service="IMySingleton, MyInterfaceAssembly"
type="MySingleton, MyImplementationAssembly" lifestyle="Singleton" />
Of course, the topic of wiring up your application to use DI is beyond my answer, but either you're using it and this answer helps you or you can take a peak at the concept and fall in love with it. :)

Using Dependency Injection frameworks for classes with many dependencies

I have been looking at various dependency injection frameworks for .NET as I feel the project I am working on would greatly benefit from it. While I think I have a good grasp of the capabilities of these frameworks, I am still a little unclear on how best to introduce them into a large system. Most demos (understandably) tend to be of quite simple classes that have one or two dependencies.
I have three questions...
First, how do you deal with those common but uninteresting dependencies, e.g. ILog, IApplicationSettings, IPermissions, IAudit. It seems overkill for every class to have these as parameters in their constructor. Would it be better to use a static instance of the DI container to get these when they are needed?
MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)
// ... versus ...
ILog log = DIContainer.Get<ILog>();
Second, how do you approach dependencies that might be used, but may be expensive to create. Example - a class might have a dependency on an ICDBurner interface but not want the concrete implementation to be created unless the CD Burning feature was actually used. Do you pass in interfaces to factories (e.g. ICDBurnerFactory) in the constructor, or do you again go with some static way of getting directly to the DI Container and ask for it at the point it is needed?
Third, suppose you have a large Windows Forms application, in which the top level GUI component (e.g. MainForm) is the parent of potentially hundreds of sub-panels or modal forms, each of which may have several dependencies. Does this mean that MainForm should be set up to have as dependencies the superset of all the dependencies of its children? And if you did so, wouldn't this end up creating a huge self-inflating monster that constructs every single class it could ever need the moment you create MainForm, wasting time and memory in the process?
Well, while you can do this as described in other answers I believe there is more important thing to be answered regarding your example and that is that you are probably violating SRP principle with class having many dependencies.
What I would consider in your example is breaking up the class in couple of more coherent classes with focused concerns and thus the number of their dependencies would fall down.
Nikola's law of SRP and DI
"Any class having more than 3
dependencies should be questioned for
SRP violation"
(To avoid lengthy answer, I posted in detail my answers on IoC and SRP blog post)
First: Add the simple dependencies to your constructor as needed. There is no need to add every type to every constructor, just add the ones you need. Need another one, just expand the constructor. Performance should not be a big thing as most of these types are likely to be singletons so already created after the first call. Do not use a static DI Container to create other objects. Instead add the DI Container to itself so it can resolve itself as a dependency. So something like this (assuming Unity for the moment)
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUnityContainer>(container);
This way you can just add a dependency on IUnityContainer and use that to create expensive or seldom needed objects. The main advantage is that it is much easier when unit testing as there are no static dependencies.
Second: No need to pass in a factory class. Using the technique above you can use the DI container itself to create expensive objects when needed.
Three: Add the DI container and the light singleton dependencies to the main form and create the rest through the DI container as needed. Takes a little more code but as you said the startup cost and memory consumption of the mainform would go through the roof if you create everything at startup time.
First:
You could inject these objects, when needed, as members instead of in the constructor. That way you don't have to make changes to the constructor as your usage changes, and you also don't need to use a static.
Second:
Pass in some sort of builder or factory.
Third:
Any class should only have those dependencies that it itself requires. Subclasses should be injected with their own specific dependencies.
I have a similar case related to the "expensive to create and might be used", where in my own IoC implementation, I'm adding automagic support for factory services.
Basically, instead of this:
public SomeService(ICDBurner burner)
{
}
you would do this:
public SomeService(IServiceFactory<ICDBurner> burnerFactory)
{
}
ICDBurner burner = burnerFactory.Create();
This has two advantages:
Behind the scenes, the service container that resolved your service is also used to resolve the burner, if and when it is requested
This alleviates the concerns I've seen before in this kind of case where the typical way would be to inject the service container itself as a parameter to your service, basically saying "This service requires other services, but I'm not going to easily tell you which ones"
The factory object is rather easy to make, and solves a lot of problems.
Here's my factory class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LVK.IoC.Interfaces;
using System.Diagnostics;
namespace LVK.IoC
{
/// <summary>
/// This class is used to implement <see cref="IServiceFactory{T}"/> for all
/// services automatically.
/// </summary>
[DebuggerDisplay("AutoServiceFactory (Type={typeof(T)}, Policy={Policy})")]
internal class AutoServiceFactory<T> : ServiceBase, IServiceFactory<T>
{
#region Private Fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly String _Policy;
#endregion
#region Construction & Destruction
/// <summary>
/// Initializes a new instance of the <see cref="AutoServiceFactory<T>"/> class.
/// </summary>
/// <param name="serviceContainer">The service container involved.</param>
/// <param name="policy">The policy to use when resolving the service.</param>
/// <exception cref="ArgumentNullException"><paramref name="serviceContainer"/> is <c>null</c>.</exception>
public AutoServiceFactory(IServiceContainer serviceContainer, String policy)
: base(serviceContainer)
{
_Policy = policy;
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoServiceFactory<T>"/> class.
/// </summary>
/// <param name="serviceContainer">The service container involved.</param>
/// <exception cref="ArgumentNullException"><paramref name="serviceContainer"/> is <c>null</c>.</exception>
public AutoServiceFactory(IServiceContainer serviceContainer)
: this(serviceContainer, null)
{
// Do nothing here
}
#endregion
#region Public Properties
/// <summary>
/// Gets the policy that will be used when the service is resolved.
/// </summary>
public String Policy
{
get
{
return _Policy;
}
}
#endregion
#region IServiceFactory<T> Members
/// <summary>
/// Constructs a new service of the correct type and returns it.
/// </summary>
/// <returns>The created service.</returns>
public IService<T> Create()
{
return MyServiceContainer.Resolve<T>(_Policy);
}
#endregion
}
}
Basically, when I build the service container from my service container builder class, all service registrations are automatically given another co-service, implementing IServiceFactory for that service, unless the programmer has explicitly registered on him/her-self for that service. The above service is then used, with one parameter specifying the policy (which can be null if policies aren't used).
This allows me to do this:
var builder = new ServiceContainerBuilder();
builder.Register<ISomeService>()
.From.ConcreteType<SomeService>();
using (var container = builder.Build())
{
using (var factory = container.Resolve<IServiceFactory<ISomeService>>())
{
using (var service = factory.Instance.Create())
{
service.Instance.DoSomethingAwesomeHere();
}
}
}
Of course, a more typical use would be with your CD Burner object. In the above code I would resolve the service instead of course, but it's an illustration of what happens.
So with your cd burner service instead:
var builder = new ServiceContainerBuilder();
builder.Register<ICDBurner>()
.From.ConcreteType<CDBurner>();
builder.Register<ISomeService>()
.From.ConcreteType<SomeService>(); // constructor used in the top of answer
using (var container = builder.Build())
{
using (var service = container.Resolve<ISomeService>())
{
service.Instance.DoSomethingHere();
}
}
inside the service, you could now have a service, a factory service, which knows how to resolve your cd burner service upon request. This is useful for the following reasons:
You might want to resolve more than one service at the same time (burn two discs simultaneously?)
You might not need it, and it could be costly to create, so you only resolve it if needed
You might need to resolve, dispose, resolve, dispose, multiple times, instead of hoping/trying to clean up an existing service instance
You're also flagging in your constructor which services you need and which ones you might need
Here's two at the same time:
using (var service1 = container.Resolve<ISomeService>())
using (var service2 = container.Resolve<ISomeService>())
{
service1.Instance.DoSomethingHere();
service2.Instance.DoSomethingHere();
}
Here's two after each other, not reusing the same service:
using (var service = container.Resolve<ISomeService>())
{
service.Instance.DoSomethingHere();
}
using (var service = container.Resolve<ISomeService>())
{
service.Instance.DoSomethingElseHere();
}
First:
You might approach it by creating a container to hold your "uninteresting" dependencies (ILog, ICache, IApplicationSettings, etc), and use constructor injection to inject that, then internal to the constructor, hydrate the fields of the service from container.Resolve() ? I'm not sure I'd like that, but, well, it's a possibility.
Alternatively, you might like to use the new IServiceLocator common interface (http://blogs.msdn.com/gblock/archive/2008/10/02/iservicelocator-a-step-toward-ioc-container-service-locator-detente.aspx) instead of injecting the dependencies?
Second:
You could use setter injection for the optional/on-demand dependencies? I think I would go for injecting factories and new up from there on-demand.
To partially answer my first question, I've just found a blog post by Jeremy Miller, showing how Structure Map and setter injection can be used to auto-populate public properties of your objects. He uses ILogger as an example:
var container = new Container(r =>
{
r.FillAllPropertiesOfType<ILogger>().TheDefault.Is
.ConstructedBy(context => new Logger(context.ParentType));
});
This means that any classes with an ILogger property, e.g.:
public class ClassWithLogger
{
public ILogger Logger { get; set; }
}
public class ClassWithLogger2
{
public ILogger Logger { get; set; }
}
will have their Logger property automatically set up when constructed:
container.GetInstance<ClassWithLogger>();

Resources