Summary: I want to know the best design for creating cross-platform (eg. desktop, web, and Silverlight) classes in C#, with no duplication of code, with the pros and cons of each design.
I'm often writing new, useful classes for one application domain; there's no reason why they won't work across domains. How can I structure my code to make it ideally cross-platform?
For example, let's say I wanted to make a generic "MyTimer" class with an interval and on-tick event. In desktop, this would use the built-in .NET timer. In Silverlight, I would use a DispatchTimer.
Design #1 might be "create a class and use pre-processor directives for conditional compilation," eg. "#IF SILVERILGHT ...". However, this leads to code that is less understandable, readable, and maintainable.
Design #2 might be "create subclasses called DesktopTimer and SilverlightTimer and consume those from MyTimer." How would that work?
While this is a trivial case, I may have more complicated classes that, for example, consume platform-specific classes (IsolatedStorage, DispatchTimer, etc.) but aren't directly replacing them.
What other designs/paradigms can I use?
I would suggest writing Interfaces that you would simply implement for your platform specific code. Then, the interfaces assure that your code will respect the contracts given by your interface, otherwise there will be a code break (if one member is not implemented).
Besides, within this library where resides your specific timer classes, to stick to your example, I would create a class for each platform, thus using the DispatchTimer for Silverlight, and the built-in .NET timer for the desktop version.
In the end, you would end up using only one interface that only its implementers know how to deal with the contract specifically to your underlying platform.
EDIT #1
Conditonal design is not an option for a good design. Here is a tool that will help you deal with the Dependancy Injection, that is called Unity Application Block, and is used to deal with such scenario like yours.
You only use an XML configuration that is very versatile to "tell" what has to be instantiated when this or that interface is needed. Then, the UnityContainer consults with the configuration you have made, and instantiate the right class for you. This assures good design approach and architecture.
EDIT #2
I'm not very familiar with Dependency Injection, and not at all familiar with Unity Application Block. Can you point to some resources or explain these a bit further?
Microsoft Enterprise Library 5.0 - April 2010;
Microsoft Unity 2.0 – April 2010;
Microsoft Unity 2.0 Documentation for Visual Studio 2008;
Are there good tutorial/walkthroughs for unity that don't use configuration files? (SO question on the topic that should provide valuable hints to start with Unity);
Specifying Types in the Configuration File;
Walkthrough: The Unity StopLight QuickStart;
Walkthrough: The Unity Event Broker Extension QuickStart.
I think these resources shall guide you through your learnings. If you need further assistance, please let me know! =)
EDIT #3
But anyway, the StopLight quickstart [...] seems to imply that the dependency mapping of interface to concrete class is done in code (which won't work for me).
In fact, you can do both code and XML dependency mapping, the choice is yours! =)
Here are some example that you should perhaps inspire from to make the StopLight quickstart use the XML configuration instead of the coded mapping.
Testing Your Unity XML Configuration;
Using Design-Time Configuration;
Source Schema for the Unity Application Block.
If this doesn't help you get through, let me know. I shall then provide a simple example using XML dependency mapping. =)
1) Interfaces with platform-specific class in their own assemblies: ITimer in a shared assembly, and a "WebAssembly" containing WebTimer, for example. Then the "WebAssembly.dll", or "DesktopAssembly.dll" are on-demand loaded. This turns it into more of a deployment/configuration issue, and everything compiles. Dependency Injection or MEF become a great help here.
2) Interfaces (again), but with conditional compilation. This makes it less of a deployment issue, and more of a compilation problem. WebTimer would have #ifdef WEB_PLATFORM around it, and so on.
Personally, I'd lean to #1 - but in a complicated application, most likely you'll end up having to use both because of slight changes in the available parts of the .net framework between silverlight and everything else. You may even want different behavior in core parts of your app just for the performance issues.
I think interfaces are a good choice here (defining what a timer will do without actually implementing it)
public interface ITimer
{
void CreateTimer(int _interval, TimerDelegate _delegate);
void StopTimer();
// etc...
} // eo interface ITimer
From this, you derive your concrete timers:
public class DesktopTimer : ITimer
{
} // eo DesktopTimer
public class SilverlightTimer : ITimer
{
} // eo class SilverlightTimer
public class WebTimer : Timer
{
} // eo class WebTimer
Then comes the fun part. How do we create the right timer? Here you could implement some kind of platform-factory that returned the right timer depending on what platform it is running on. Here is a quick and dirty idea (I would make it more dynamic than this, and perhaps implement one factory for multiple kinds of classes, but this is an example)
public enum Platform
{
Desktop,
Web,
Silverlight
} // eo enum Platform
public class TimerFactory
{
private class ObjectInfo
{
private string m_Assembly;
private string m_Type;
// ctor
public ObjectInfo(string _assembly, string _type)
{
m_Assembly = _assembly;
m_Type = _type;
} // eo ctor
public ITimer Create() {return(AppDomain.CurrentDomain.CreateInstanceAndUnwrap(m_Assembly, m_Type));}
} // eo class ObjectInfo
Dictionary<Platform, ObjectInfo> m_Types = new Dictionary<PlatForm, ObjectInfo>();
public TimerFactory()
{
m_Types[Platform.Desktop] = new ObjectInfo("Desktop", "MyNamespace.DesktopTimer");
m_Types[Platform.Silverlight] = new ObjectInfo("Silverlight", "MyNameSpace.SilverlightTimer");
// ...
} // eo ctor
public ITimer Create()
{
// based on platform, create appropriate ObjectInfo
} // eo Create
} // eo class TimerFactory
As I mentioned above, I would not have a factory for every time of object, but make a generic platform-factory that could handle timers, containers and whatever else you want. This is just an example.
The Model-View-Presenter pattern is a really good approach if you want to separate all of your user interface logic from the actual GUI framework you are using. Read Michael Feather's article "The Humble Dialog Box" to get an excellent explanation of how it works:
http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf
The original article was made for C++, if you want a C# example, look here:
http://codebetter.com/blogs/jeremy.miller/articles/129546.aspx
The Pros are:
you will make your GUI logic resusable
your GUI logic becomes applicable for unit testing
The Cons:
if your program does not need more than one GUI framework, this approach produces more lines-of-code, and you have to deal with more complexity, since you have to decide all through your coding which parts of your code belong into the view and which into the presenter
Go with all OOD you know. I'd suggest creating platform-agnostic (Windows, Mono/destkop, web) domain model. Use abstract classes to model platform-dependant stuff (like the Timer). Use Dependency Injection and/or Factory patterns to use specific implementations.
EDIT: at some point you have to specify what concrete classes to use, but using the abovementioned patterns can bring all that code into one place without using conditional compilation.
EDIT: an example of DI/Factory. Of course you can use on of existing frameworks, which will give you more power and expressivenes. For the simple example it seems like an overkill, but the more complicated the code, the bigger the gain of using the patterns.
// Common.dll
public interface IPlatformInfo
{
string PlatformName { get; }
}
public interface PlatformFactory
{
IPlatformInfo CreatePlatformInfo();
// other...
}
public class WelcomeMessage
{
private IPlatformInfo platformInfo;
public WelcomeMessage(IPlatformInfo platformInfo)
{
this.platformInfo = platformInfo;
}
public string GetMessage()
{
return "Welcome at " + platformInfo.PlatformName + "!";
}
}
// WindowsApp.exe
public class WindowsPlatformInfo : IPlatformInfo
{
public string PlatformName
{
get { return "Windows"; }
}
}
public class WindowsPlatformFactory : PlatformFactory
{
public IPlatformInfo CreatePlatformInfo()
{
return new WindowsPlatformInfo();
}
}
public class WindowsProgram
{
public static void Main(string[] args)
{
var factory = new WindowsPlatformFactory();
var message = new WelcomeMessage(factory.CreatePlatformInfo());
Console.WriteLine(message.GetMessage());
}
}
// MonoApp.exe
public class MonoPlatformInfo : IPlatformInfo
{
public string PlatformName
{
get { return "Mono"; }
}
}
public class MonoPlatformFactory : PlatformFactory
{
public IPlatformInfo CreatePlatformInfo()
{
return new MonoPlatformInfo();
}
}
public class MonoProgram
{
public static void Main(string[] args)
{
var factory = new MonoPlatformFactory();
var message = new WelcomeMessage(factory.CreatePlatformInfo());
Console.WriteLine(message.GetMessage());
}
}
As others have sugested, interfaces are the way to go here. I would alter the interface from sugestion Moo-Juice suggestion slightly...
`
//Why is this block not formated like code???
public interface ITimer{
void StopTimer(); // etc...
void StartTimer(); // etc...
TimeSpan Duration {get;} // eo interface ITimer
}`
Now you would need to get the ITimer into your class that is using it. The most timple way to do this is called dependency injection. The most common approach to achieve this is called constructor injection.
So when creating a class that needs a timer you pass a timer into the class when creating one.
Basically you do:
var foo = new Foo(new WebTimer());
Since that will get complicated quite fast, you can utilize some helpers. This pattern is called inversion of control. There are some frameworks that will help you, like the ninject or castle windsor.
Both are inversion of control (IOC) containers. (Thats the secret sauce)
Basically you "register" your timer in the IOC, and also register your "Foo". When you need a "Foo", you ask your IOC Container to create one. The container looks at the constructor, finds that it needs a ITimer. It will then create an ITimer for you, and pass it into the constructor, and finally hand you the complete class.
Inside you class you dont need to have any knowledge about the ITimer, or how to create it, since all that was moved to the outside.
For different Applications you now only need to register the correct components, and you are done...
P.s.: Be carefull and dont confuse the IOC Container with a service locator...
Links:
http://ninject.org/download
http://www.castleproject.org/container/index.html
http://www.pnpguidance.net/Category/Unity.aspx
Why not have configuration section which will tell your library about the platform of the host application. This you have to set only once in your application to the host config file (web.config or app.config), and rest you can use using Factory method as suggested by Moo-Juice. You can use platform detail over entire functionality of the library.
Related
I am developing an internal library that is to be used by other developers in the company that I'm working for. I am applying SOLID patterns and following the best practices as described in Dependency Inject (DI) “friendly” library.
My end users would be developers of different applications. Some of them are complex legacy applications with no DI, and others are newer apps that have DI and TDD.
Now, I am trying to figure out how to call this DI friendly library from a legacy ASP.NET Webforms application that has no DI implemented in it, and obviously, I can't revise 250+ aspx pages to support constructor injection because it is out of scope of my project. (Yes, I have read Introducing an IoC Container to Legacy Code
)
One idea that I had was creating a static global wrapper for Common Service Locator to automatically resolve dependencies throughout the app:
public static class GlobalResolver
{
public static T Resolve<T>()
{
return ServiceLocator.Current.GetInstance<T>();
}
}
The nice thing about this approach is that I can use any IoC library in my composition root (I currently use Unity). I would use this GlobalResolver like this:
protected void OnClick(object sender, EventArgs e)
{
IMailMessage message = MessageFactory.Create("Jack.Daniels#jjj.com", "John.Doe#jjj.com", "subject", "Body", true, MailPriority.High);
GlobalResolver.Resolve<IMailer>().SendMail(message);
}
I like this approach and I think it's clean, but novice developers in my company might get confused with this GlobalResolver.Resolve<IMailer> line, so I'm trying to see if there is alternative to this out there.
One thing that comes to my mind is something like this:
public static class CommonCatalog
{
public static IMailer Mailer => ServiceLocator.Current.GetInstance<IMailer>();
public static IMailMessageFactory MessageFactory => ServiceLocator.Current.GetInstance<IMailMessageFactory>();
public static IFtpSecureClientFactory FTPClientFactory => ServiceLocator.Current.GetInstance<IFtpSecureClientFactory>();
// And so on...
}
And simply use it like this: CommonCatalog.Mailer.SendMail(message);. Developers at my company are used to seeing static methods, and I think this approach might be desirable for them.
My questions are:
Is this the best solution for my problem?
Am I violating any of the best practices?
Is there a design pattern that descibes the CommonCatalog class? Is it a "Facade" or "Proxy"?
TLDR: Developers at my company like to use Static methods, but static methods are incompatible with DI and SOLID practices. Is there any way to trick people into thinking that they are using static methods, but behind the scenes call DI code?
If you want to avoid the Service Locator anti-pattern (which you should, because - it's an anti-pattern), then the first option with a GlobalResolver is out of the question, because it's definitely a Service Locator.
The catalog of services is closer to the Facades I recommend in my expanded article on DI-friendly libraries, although I usually prefer not having an aggregated catalog of objects. It always makes me uncomfortable when I don't know how to name objects, and a name like CommonCatalog seems too devoid of meaning.
Rather, I'd prefer making instance-based Facades with the Fluent Builder pattern as described in the article, since it tends to be more flexible when you, down the line, discover that you need to add various options and switches to the facade.
If you absolutely must, though, you can add a static method for each of the Facades. Something like this:
public static class Mailer
{
public static IMailer Default
{
get { return new MailerBuilder().Create(); }
}
}
If the instance conceivably has Singleton lifetime, you can, instead, use the Singleton design pattern, as the next example demonstrates.
You could implement a default MessageFactory the same way, but here instead using the Singleton design pattern:
public static class MailMessageFactory
{
public static IMailMessageFactory Default { get } =
new MailMessageFactoryBuilder().Create();
}
Notice that this doesn't use a Service Locator for the implementation, either.
To be clear, though, what's behind such Facades could easily be implemented according to the SOLID principles, but the calling code would still have a hard time doing that.
I am planning to write a shared file between that could be used between multiple projects.
My Projects:
Write code to eat Ice cream. (Because ice cream is my favorite food).
(Please note that my favorite food might change to Mango in the future)
Write code to eat Mango. (Because mango is my favorite food).
(Please note that my favorite food might change to Ice cream in the future)
Following is the interface
interface IEatFavoriteFood
{
void eat();
}
Following will be my concrete classes.
class EatMango
{
void eat()
{
// Some code to eat mango
}
}
class EatIceCream
{
void eat()
{
// Some code to eat ice cream
}
}
So, I will need to have two main programs separately for my two projects, since I will be initializing two different concrete classes for the IEatFavoriteFood interface to call eat().
Main()
{
IEatFavoriteFood iff = new EatMango();
iff.eat();
}
and
Main()
{
IEatFavoriteFood iff = new EatIceCream();
iff.eat();
}
In addition to that, if sometime in the future the favorite food changes to Mango in the first project, then I will have to re-write the initialization and re-compile my project. Is there a better way to implement this functionality. Does using a config file in this case, makes better sense?
For dependency injection to work, you need some place where the concrete types are listed, which knows which concrete class to plug into for your possible dependencies (the interface).
In dependency injection frameworks, this is often done with some kind of configuration, either via code or with some external files (e.g. some XML configuration).
For your purpose, it’s probably the easiest way to start simple and simply have some “central entity” that provides you with your dependencies. This could for example be a FavoriteFoodFactory:
public class FavoriteFoodFactory
{
public static IEatFavoriteFood GetFavoriteFood()
{
return new EatIceCream();
}
}
So in your Main, you would then just ask that factory to give you whatever favorite food is currently configured:
Main()
{
IEatFavoriteFood iff = FavoriteFoodFactory.GetFavoriteFood();
iff.eat();
}
Of course that just shifts the responsibility to create a concrete object to somewhere else, but that’s exactly the point of dependency injection. To have something at the very top that takes care of how to resolve a dependency, removing the need to know from the components further down.
I would suggest you to use an IOC container like Autofac (http://autofac.org/), Ninject (http://www.ninject.org/) or whatever you like most.
The container will provide you with different ways to handle that kind of scenario.
For example, in Autofac you can create a module (that is a class containing the registrations of the concrete classes that will be used by the container) that can be loaded/selected via web.config or code.
You can see a detailed documentation here with examples
http://docs.autofac.org/en/latest/configuration/modules.html
Please note that using an IOC container can be easy, but in most cases you must be aware of the components lifecycle in order to avoid possible problems and memory leaking.
I have a class which contains a view dependencies (all interfaces). Basically the behavior of the class is defined through the implementation of those interfaces. I want to be able to have a "builder" which can create instances of this class with different implementations of the interfaces(or parts of it). Something like this:
public class API
{
private readonly ISomeInterface _someInterface;
private readonly ISomeOtherInterface _someOtherInterface;
private readonly ISomeAnotherInterface _someAnotherInterface;
API(ISomeInterface someInterface,ISomeOtherInterface someOtherInterface,ISomeAnotherInterface someAnotherInterface)
{*/implementation ommitted*/}
//Example method
public void DoSomethingWhichDependsOnOneOrMoreInterfaces()
{
//somecode
id(_someInterface != null)
_someInterface.SomeMethode();
}
public class MyApiBuilder()
{
// implementation ommitted
API CreateAPI(someEnum type)
{
switch(type)
{
case SpecificAPI32:
var speficImplementationOfSomeInterface = new ImplementsISomeInterface();
speficImplementationOfSomeInterface .Setup("someSetup");
var specificImplementationOfOtherInterface = new ImplementsISomeOtherInterface();
returns new API(speficImplementationOfSomeInterface,specificImplementationOfOtherInterface ,null);
}
}
}
What is the most elegant way of implementing this (if this makes sense at all)? I was first thinking of the Builder Design Patterns but as far as I understood it, its slightly different.
[Edit]
As pointed out, the way I am implementing it is a factory method but I am not fully satisfied with it. The API can contain a varity of different interfaces which can be totally independent of each other but some may depend on others.(but not mandatory) I would like to give the user (the developer using this "API") as much freedom as possible in creating the API he wants to use. Lets try to explain what I am basically up to:
Let's say I am developing a plugin for a game engine which can post achievments and other stuff to various social media channels. So basically there could be a Interface which implements the access to twitter,facebook,youtube,whathever or some custom server. This custom server could need some kind of authentification process. The user should be able to build at start the API in a nice (hmm fluent is nice..) way. So basically something like this:
var myTotallyForMyNeedsBuildAPI = API.CreateCustomApi().With(Api.Twitter).And(Api.Facebook).And(Api.Youtube).And(Api.CustomServer).With(Security.Authentification);
I actually do not know how to make that fluent but something like this would be nice.
It's a good practice to use Dependency Injection as you want to give the programmer the ability to compose the object with desired configuration.
Check MEF and Unity frameworks which are great for this job.
For example in Unity you can write this:
// Introducing an implementation for ISomeInterface
container.Register<ISomeInterface, SomeImplementation>();
// Introducing an implementation for ISomeOtherInterface
container.Register<ISomeOtherInterface, SomeOtherImplementation>();
// Introducing an implementation for ISomeAnotherInterface
container.Register<ISomeAnotherInterface, SomeAnotherImplemenation>();
container.Register<API, API>();
// and finally unity will compose it for you with desired configurations:
var api = container.Resolve<API>();
In this scenario the api will be composed with desired implementations.
What you have implemented is the Factory method pattern.
It's perfectly fine for what you are trying to do, but you could have a look at the other factory patterns (i.e. here) based on your context and how you think you're code will evolve in the future.
Anyway, I will also consider to not tie this three interface together in a single factory. If they are really so tighten together to be consumed together and built together, maybe they should not be three different interfaces in the first place, or at least all three implemented by the same class, so your factory will build the appropriate class with the proper implementation of these.
Probably what you are after is the Decorator pattern.
In your API class you invoke each interface if they have been provided to the API instance, which is the behaviour of the Decorator pattern.
With this pattern you obtain a modular implementation that allow you to add multiple behaviours to your API.
Here is my question...
I work in Telecom industry and have a piece of software which provides the best network available for a given service number or a site installation address. My company uses the network of the wholesale provider and we have our own network as well. To assess what services a customer might be able to get, I call a webservice to find out the services available on a given telephone exchange and based on the services available, I need to run some checks against either our network or the network of the wholesale provider.
My question is how this can be modelled using interfaces in C#? The software that I have does not make use of any interfaces and whatever classes are there are just to satisfy the fact that code cannot live outside classes.
I am familiar with the concept of interfaces, at least on theoretical level, but not very familiar with the concept of programming to interfaces.
What I am thinking is along the following lines:
Create an interface called IServiceQualification which will have an operation defined : void Qualify(). Have two classes called QualifyByNumber and QualifyByAddress and both of these implement the interface and define the details of the operation Qualify. Am I thinking along the right lines or is there a different/better way of approaching this issue.
I have read a few examples of programming to interfaces, but would like to see this utilized in a work situation.
Comments/suggestions are most welcome.
I would probably make it go a little bit deeper, but you are on the right track. I would personally create IServiceQualification with a Qualify method and then below that an abstract class called ServiceQualification which would have an abstract method called Qualify that any kind of qualifier class could implement. This lets you define common behavior among your qualifiers (there is bound to be some) while still creating the separation of concerns at a high level.
Interfaces have a defined purpose and using them properly lets you implement in any way you want without having your code require that implementation. So, we can create a service that looks something like:
public bool ShouldQualify(IServiceQualification qualification)
And no matter the implementation we send it, this method will work. It becomes something you never have to change or modify once its working. Additionally, it leads you directly to bugs. If someone reports that qualifications by address aren't working, you know EXACTLY where to look.
Take a look at the strategy design pattern. Both the problem and the approach that you have described sound like a pretty close fit.
http://www.dofactory.com/Patterns/PatternStrategy.aspx
You should think of interfaces in terms of a contract. It specifies that a class implements certain function signatures meaning you class can call them with known parameters and expect a certain object back - what happens in the middle is upto the developer of the interface to decide. This loose coupling makes your class system a lot more flexible (it has nothing to do with saving key strokes surfash)
Heres an example which is roughly aimed at your situation (but will require more modelling).
public interface IServiceQualification{
bool Qualifies(Service serv);
}
public class ClientTelephoneService : IServiceQualification
{
public bool Qualifies(Service serv){
return serv.TelNumber.Contains("01234");
}
}
public class ClientAddressService : IServiceQualification
{
public bool Qualifies(Service serv){
return serv.Address.Contains("ABC");
}
}
//just a dummy service
public class Service{
public string TelNumber = "0123456789";
public string Address = "ABC";
}
//implementation of a checker which has a list of available services and takes a client who implements the
//interface (meaning we know we can call the Qualifies method
public class ClassThatReturnsTheAvailableServices
{
//ctor
List<Service> services = //your list of all services
public List<Service> CheckServices(IServiceQualification clientServiceDetails)
{
var servicesThatQualify = new List<Service>();
foreach(var service in services){
if(clientServiceDetails.Qualifies(service)){
services.Add(service);
}
}
return servicesThatQualify;
}
}
I decided to start using Ninject and face an issue. Say I have the following scenario.
I have an IService interface and 2 classes implementing this interface. And also I have a class, which has a constructor getting IService and an int. How can I create an instance of this class with Ninject (I dont want to hardwire this int, I want to pass it every time I get an instance)?
Here's some code illustrating the situation:
interface IService
{
void Func();
}
class StandardService : IService
{
public void Func()
{
Console.WriteLine("Standard");
}
}
class AlternativeService : IService
{
public void Func()
{
Console.WriteLine("Alternative");
}
}
class MyClass
{
public MyClass(IService service, int i)
{
this.service = service;
}
public void Func()
{
service.Func();
}
IService service = null;
}
class Program
{
static void Main(string[] args)
{
IKernel kernel = new StandardKernel(new InlineModule(
x => x.Bind<IService>().To<AlternativeService>(),
x => x.Bind<MyClass>().ToSelf()));
IService service = kernel.Get<IService>();
MyClass m = kernel.Get<MyClass>();
m.Func();
}
}
The With.ConstructorArgument existed in 1.0 for this purpose. In 2.0, the syntax has changed slightly:-
With.Parameters.ConstructorArgument with ninject 2.0
See Inject value into injected dependency for more details and examples of how to use the context, providers and arguments to pass stuff like this around more correctly.
EDIT: As Steven has elected to pretend my comment is irrelevant, I'd best make clear what I'm saying with some examples (for 2.0):
MyClass m = kernel.Get<MyClass>( new ConstructorArgument( "i", 2) );
which to my eyes is very clear and states exactly what's happening.
If you're in a position where you can determine the parameter in a more global way you can register a provider and do it like this:
class MyClassProvider : SimpleProvider<MyClass>
{
protected override MyClass CreateInstance( IContext context )
{
return new MyClass( context.Kernel.Get<IService>(), CalculateINow() );
}
}
And register it like this:
x => x.Bind<MyClass>().ToProvider( new MyClassProvider() )
NB the CalculateINow() bit is where you'd put in your logic as in the first answer.
Or make it more complex like this:
class MyClassProviderCustom : SimpleProvider<MyClass>
{
readonly Func<int> _calculateINow;
public MyClassProviderCustom( Func<int> calculateINow )
{
_calculateINow = calculateINow;
}
protected override MyClass CreateInstance( IContext context )
{
return new MyClass( context.Kernel.Get<IService>(), _calculateINow() );
}
}
Which you'd register like so:
x => x.Bind<MyClass>().ToProvider( new MyClassProviderCustom( ( ) => new Random( ).Next( 9 ) ) )
UPDATE: Newer mechanisms which exhibit much improved patterns with less boilerplate than the above are embodied in the Ninject.Extensions.Factory extension, see:
https://github.com/ninject/ninject.extensions.factory/wiki
As stated earlier, if you need to pass a different parameter each time and you have multiple levels in the dependency graph, you might need to do something like this.
A final consideration is that because you haven't specified a Using<Behavior>, it's going to default to the default as specified/defaulted in the options for the kernel (TransientBehavior in the sample) which might render fact that the factory calculates i on the fly moot [e.g., if it the object was being cached]
Now, to clarify some other points in the comments that are being FUDed and glossed over. Some important things to consider about using DI, be it Ninject or whatever else is to:
Have as much as possible done by constructor injection so you dont need to use container specific attributes and tricks. There's a good blog post on that called Your IoC Container is Showing.
Minimise code going to the container and asking for stuff - otherwise your code is coupled to a) the specific container (which the CSL can minimise) b) the way in which your entire project is laid out. There are good blog posts on that showing that CSL isnt doing what you think it does. This general topic is referred to as Service Location vs Dependency Injection. UPDATE: See http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx for a detailed and complete rationale.
Minimise use of statics and singletons
Don't assume there is only one [global] container and that it's OK to just demand it whenever you need it like a nice global variable. The correct use of multiple modules and Bind.ToProvider() gives you a structure to manage this. That way each separate subsystem can work on its own and you wont have low-level components being tied to top-level components, etc.
If someone wants to fill in the links to the blogs I'm referring to, I'd appreciate that (they're all already linked from other posts on SO though, so all of this is just duplication UI've introduced with the aim of avoiding the confusion of a misleading answer.)
Now, if only Joel could come in and really set me straight on what's nice syntax and/or the right way to do this!
UPDATE: While this answer is clearly useful from the number of upvotes it's garnered, I'd like to make the following recommendations:
The above feels as it's a bit dated and to be honest reflects a lot of incomplete thinking which almost feels embarassing since reading Dependency Injection in .net - Run and buy it now - it's not just about DI, the first half is a complete treatment of all the architecture concerns surrounding it from a man who has spent way too much time here hanging around the dependency injection tag.
Go read Mark Seemann's top rated posts here on SO right now - you'll learn valuable techniques from every one