-
Notifications
You must be signed in to change notification settings - Fork 5
Models.Features
Models.Features defines simple interface IFeatureModel
with single method bool TryWith<TFeature>(out TFeature feature)
. Implementing this interface you are saying 'This component can provide you other components'. This way we can do 'feature-based decisions'.
For e.g.: Lets say we are inside HTTP request (so we have HTTP context component - implementing IFeatureModel
) and if hosting (creator of HTTP context) supports it, we want to ugrade current request to web socket request. So we simply test whether current HTTP context supports feature IWebSocketContext
and if it does, we can use current HTTP context as such component.
public void HandleRequest(IHttpContext httpContext)
{
IWebSocketContext webSocketContext;
if (httpContext.TryWith(out webSocketContext))
{
HandleWebSocketRequest(webSocketContext);
return;
}
//TODO: Handle request standardly...
}
There are two implementations of IFeatureModel
for two main use-cases shipped with the library.
Beside TryWith
method, you can use With
extension in case when you require that feature and want to throw exception, if such feature it not supported (by the feature model).
// If IWebSocketContext is not supported by httpContext, exception is thrown.
IWebSocketContext webSocketContext = httpContext.With<IWebSocketContext>();
Class ObjectFeatureModel
provides feature-list based on implemented interfaces of single object (passed-in in the constructor), so implementation creates tiny wrap of casting object using as
operator and testing whether target object is or is not null
.
var storage = new FileAndSessionAndTempStorage();
IFeatureModel context = new ObjectFeatureModel(storage);
...
IFileStorage fileStorage;
if (context.TryWith(out fileStorage))
{
//TODO: Some whatever with fileStorage.
}
ISessionStorage sessionStorage;
if (context.TryWith(out sessionStorage))
{
//TODO: Some whatever with sessionStorage.
}
ITempStorage tempStorage;
if (context.TryWith(out tempStorage))
{
//TODO: Some whatever with tempStorage.
}
Class FeatureCollectionModel
provides ability to compose features based on feature type. This implementation has methods for mapping features to feature types, internally it creates dictionary of type->object (target feature object).
IFeatureModel context = new FeatureCollectionModel()
.Add<IFileStorage>(new FileStorage())
.Add<ISessionStorage>(new SessionStorage())
.Add<ITempStorage>(new TempStorage());
...
IFileStorage fileStorage;
if (context.TryWith(out fileStorage))
{
//TODO: Some whatever with fileStorage.
}