Dynamic context injection in Specflow - specflow

Using Specflow's basic dependency injection, it is possible to inject a dynamic context object as below.
This saves having to use the dictionary which I find clunky, are there drawbacks to this approach?
public class TestClass
{
private readonly dynamic context;
public TestClass(ExpandoObject context)
{
this.context = context;
}
[Given(#"I have a file")]
public void GivenIHaveAFile()
{
context.FilePath = #".\Folder\File";
}
[When(#"I use the file")]
public void GivenIHaveAFile()
{
var fileContents = File.ReadAllText(context.FilePath);
}
}

The drawbacks are only those that you get with using dynamic objects in general. You'll get no intellisense and won't be able to add any behaviour to your object.
Personally I prefer to use specific classes to handle passing state between steps as these objects can then be assigned behaviour as well as holding data, but YMMV.
In place of the generic dictionary though this seems reasonable, as it at least avoids the casting.

Related

Instance method with Guice

I would like to have a static instance method with Guice for one of the components (non-managed bean should be able to access this class). I created something like this:
public class LookupService {
#Inject
private static Provider<Injector> injector = null;
private final ILookup<IWS> lookup;
#Inject
public LookupService(ILookup<IWS> lookup) {
this.lookup = lookup;
}
public static LookupService instance() {
return injector.get().getInstance(LookupService.class);
}
public <T extends IWS> T lookup(Class<T> localInterface) {
return lookup.lookup(localInterface);
}
}
What do you think about this design ? Any other ideas on this ? (accessing managed beans from non-managed objects)
Basically, the pattern you're looking for is called "requesting static injection" and there's a Binder method dedicated to it. Once you have that down, your code looks a lot like this example from the Guice docs.
public class MainModule extends AbstractModule {
#Override public void configure() {
requestStaticInjection(LookupService.class);
}
}
public class LookupService {
/** This will be set as soon as the injector is created. */
#Inject
static Provider<LookupService> provider = null;
private final ILookup<IWS> lookup;
#Inject
public LookupService(ILookup<IWS> lookup) {
this.lookup = lookup;
}
public static LookupService instance() {
return provider.get();
}
public <T extends IWS> T lookup(Class<T> localInterface) {
return lookup.lookup(localInterface);
}
}
A few notes:
While you can still set your field to be private, remember that this means you cannot set it in tests (or in future non-Guice usage) without Guice's private-field-access magic. When using injected fields, we often make them package-private and then put the tests in the same package.
Static injection is generally seen as something to endorse only when migrating to Guice, or when you use other code you can't change. When possible, try to avoid global state--even if this means making FooBean data-only and creating an injected FooBeanService.
Even though you can inject an Injector wherever you'd like, you might find it easier to test if you simply inject a Provider<LookupService> instead. Only inject an Injector if you don't know what type you're going to need until runtime--for example, if you implement LookupService.lookup(...) using an Injector by passing the class literal to the injector to get an instance.
In fact, it's hard to say from here, but ILookup seems to act a lot like the Service Locator pattern, which solves the exact type of problem that Guice solves with dependency injection! If that's the case, you might as well rewrite ILookup to use Guice: Just remove calls to LookupService.instance().lookup(Foo.class) and instead create a matching pair of #Inject static Provider<Foo> fooProvider and requestStaticInjection(FooUser.class).
Hope that helps!

Google Guice and varying injections at runtime

I'd like to vary the injected implementations based on something that's not known until runtime. Specifically, I'd like my app to operate as different versions where the "version" is not determined until a request is executing. Also, the "version" could vary per request.
After reading the docs it seems that I could implement a providers in cases where I need to choose an implementation at runtime based on the "version". Additionally, I could roll my own on top of juice.
Is implementing a provider the best way to go in this scenario? I'd like to know if there is a best practice or if anyone else out there has tried to use Guice to tackle this problem.
Thanks for any help!
-Joe
I think that if the version can be known only at runtime, you must provide the versioned "services" manually with custom provider. Possibly something like this:
#Singleton
public abstract class VersionedProvider<T, V> {
private Map<V, T> objects;
T get(V version) {
if (!objects.containsKey(version)) {
objects.put(version, generateVersioned(version));
}
return objects.get(version);
}
// Here everything must be done manually or use some injected
// implementations
public abstract T generateVersioned(V version);
}
public class MyRuntimeServiceModule extends AbstractModule {
private final String runTimeOption;
public ServiceModule(String runTimeOption) {
this.runTimeOption = runTimeOption;
}
#Override protected void configure() {
Class<? extends Service> serviceType = option.equals("aServiceType") ?
AServiceImplementation.class : AnotherServiceImplementation.class;
bind(Service.class).to(serviceType);
}
}
public static void main(String[] args) {
String option = args[0];
Injector injector = Guice.createInjector(new MyRuntimeServiceModule(option));
}

How to create ObjectQuery for testing EF4 'Include' method

We are using EF4 and creating test cases for DAL layer (DAL layer is having linq query). We are using TypeMock as mocking framework. For testing, we are creating Fakecontext of ObjectContext and mocking CreateObjectSet method as follows:
Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable());
The above is working fine. The issue is when we are trying to include related tables using 'Include'. We have extended the include method as follows:
public static IQueryable<T> Include<T>(this IQueryable<T> source, Expression<Func<T>> property)
{
var objectQuery = source as ObjectQuery<T>;
if (objectQuery != null)
{
var propertyPath = GetPropertyPath(property);
return objectQuery.Include(propertyPath);
}
return source;
}
So what happen is, in the above Include method the source type should be ObjectQuery<T>. But as we have mocked CreateObjectSet, source type in Include method is of Collection.Generic.List type. Kindly let us know how should we mock in the above case. Your timely help will be highly appreciable. Thanks
Object Services can be difficult to use when writing unit test. Unfortunately, there is not a good interface to mock for ObjectQuery<T> as you have found out. To handle this scenario I have created a wrapper class following the Repository pattern to encapsulate my ObjectContext and created a wrapper class to encapsulate ObjectQuery<T>:
public interface IMyObjectQuery<T> : IOrderedQueryable<T>
{
IMyObjectQuery<T> Include(string path);
}
public class MyObjectQuery<T> : IMyObjectQuery<T>
{
private ObjectQuery<T> _query;
public MyObjectQuery(ObjectQuery<T> query)
{
_query = query;
}
IMyObjectQuery<T> Include(string path)
{
//There is probably a better way to do this
//but you get the idea
return new MyObjectQuery(_query.Include(path));
}
//Implement IQueryable, IEnumerable...
}
And then it is a matter of implementing a Repository wrapper for your ObjectContext. Here is a link to get you started.
Add something like this:
public class MyRepository : IMyRespository
{
...
public IMyObjectQuery<T> CreateQuery<T>()
{
return new MyObjectQuery(_context.CreateQuery<T>());
}
...
}
This is probably not the simple solution that you were looking for, as it is not a trivial task. I think you will find that if you don't you will continue to encounter difficulty writing tests.

How do I handle classes with static methods with Ninject?

How do I handle classes with static methods with Ninject?
That is, in C# one can not have static methods in an interface, and Ninject works on the basis of using interfaces?
My use case is a class that I would like it to have a static method to create an
unpopulated instance of itself.
EDIT 1
Just to add an example in the TopologyImp class, in the GetRootNodes() method, how would I create some iNode classes to return? Would I construct these with normal code practice or would I somehow use Ninject? But if I use the container to create then haven't I given this library knowledge of the IOC then?
public interface ITopology
{
List<INode> GetRootNodes();
}
public class TopologyImp : ITopology
{
public List<INode> GetRootNodes()
{
List<INode> result = new List<INode>();
// Need code here to create some instances, but how to without knowledge of the container?
// e.g. want to create a few INode instances and add them to the list and then return the list
}
}
public interface INode
{
// Parameters
long Id { get; set; }
string Name { get; set; }
}
class NodeImp : INode
{
public long Id
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string Name
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
// Just background to highlight the fact I'm using Ninject fine to inject ITopology
public partial class Form1 : Form
{
private ITopology _top;
public Form1()
{
IKernel kernal = new StandardKernel(new TopologyModule());
_top = kernal.Get<ITopology>();
InitializeComponent();
}
}
If you're building a singleton or something of that nature and trying to inject dependencies, typically you instead write your code as a normal class, without trying to put in lots of (probably incorrect) code managing the singleton and instead register the object InSingletonScope (v2 - you didnt mention your Ninject version). Each time you do that, you have one less class that doesnt surface its dependencies.
If you're feeling especially bloody-minded and are certain that you want to go against that general flow, the main tools Ninject gives you is Kernel.Inject, which one can use after you (or someone else) has newd up an instance to inject the dependencies. But then to locate one's Kernelm you're typically going to be using a Service Locator, which is likely to cause as much of a mess as it is likely to solve.
EDIT: Thanks for following up - I see what you're after. Here's a hacky way to approximate the autofac automatic factory mechanism :-
/// <summary>
/// Ugly example of a not-very-automatic factory in Ninject
/// </summary>
class AutomaticFactoriesInNinject
{
class Node
{
}
class NodeFactory
{
public NodeFactory( Func<Node> createNode )
{
_createNode = createNode;
}
Func<Node> _createNode;
public Node GenerateTree()
{
return _createNode();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToMethod( context => () => Kernel.Get<Node>() );
}
}
[Fact]
public void CanGenerate()
{
var kernel = new StandardKernel( new Module() );
var result = kernel.Get<NodeFactory>().GenerateTree();
Assert.IsType<Node>( result );
}
}
The ToMethod stuff is a specific application of the ToProvider pattern -- here's how you'd do the same thing via that route:-
...
class NodeProvider : IProvider
{
public Type Type
{
get { return typeof(Node); }
}
public object Create( IContext context )
{
return context.Kernel.Get<Node>();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToProvider<NodeProvider>();
}
}
...
I have not thought this through though and am not recommending this as A Good Idea - there may be far better ways of structuring something like this. #Mark Seemann? :P
I believe Unity and MEF also support things in this direction (keywords: automatic factory, Func)
EDIT 2: Shorter syntax if you're willing to use container-specific attributes and drop to property injection (even if Ninject allows you to override the specific attributes, I much prefer constructor injection):
class NodeFactory
{
[Inject]
public Func<Node> NodeFactory { private get; set; }
public Node GenerateTree()
{
return NodeFactory();
}
}
EDIT 3: You also need to be aware of this Ninject Module by #Remo Gloor which is slated to be in the 2.4 release
EDIT 4: Also overlapping, but not directly relevant is the fact that in Ninject, you can request an IKernel in your ctor/properties and have that injected (but that doesn't work directly in a static method).

Castle Windsor: How to prevent circular references in factory-created objects were the created objects refers back to the factory

I am using windsor castle as my IoC container, and has run in to a bit of a problem. This is best explained in code, so I´ll give it a try.
I have a factory class, that should provide me with implementations of a certain interface:
public interface IObjectCreatorFactory
{
IObjectCreator GetObjectCreator(Type objectType);
}
public interface IObjectCreator
{
T CreateObject<T>(IDataRow data);
bool SupportsType(Type type);
}
Implementation of the factory class could look like this, though I am not sure this is the way to go:
public interface ObjectCreatorFactory:IObjectCreatorFactory
{
IEnumerable specificCreators;
IObjectCreator defaultCreator;
public ObjectCreatorFactory(IEnumerable<IObjectCreator> specificCreators, IObjectCreator defaultCreator)
{
this.specificCreators= specificCreators;
this.defaultCreator= defaultCreator;
}
public IObjectCreator GetObjectCreator(Type objectType)
{
foreach (IObjectCreator creator in specificCreators)
{
if (creator.SupportsType(objectType))
{
return creator;
}
}
return defaultCreator;
}
}
Now this would work out ok, but if I want my IObjectCreator instance to create child objects using a specific IObjectCreator, i would like to call ObjectCreatorFactory, and this obviously results in a circular reference:
public void SpecificObjectCreator:IObjectCreator
{
IObjectCreatorFactory objCreatorFactory;
public SpecificObjectCreator(IObjectCreatorFactory objCreatorFactory)
{
this.objCreatorFactory = objCreatorFactory;
}
T CreateObject<T>(IDataRow data)
{
T obj = new T;
ChildObject childObject = objCreatorFactory.GetObjectCreator(typeof(ChildObject)).CreateObject<ChildObject>(data);
.......
}
bool SupportsType(Type type);
}
This does not work out. What would be the way to go for this scenario, where the created objects are refering back to the factory for child object creators?
I would simply move the factory out of the constructors of the various specific object creators, and introduce a method on the IObjectCreator interface instead, responsible for initialising the creators:
public interface IObjectCreator
{
T CreateObject<T>(IDataRow data);
bool SupportsType(Type type);
void Initialize(IObjectCreatorFactory factory);
}
And then just invoke Initialze(this) on each object creator passed into the factory.
In the past I've used custom life cycle stages to take care of automatically invoking "post-construction" setup of components to both avoid circular dependencies and also to take care of other associated concerns (i.e. applying additional component configuration from an external source like a database) - but it's probably overkill for what you need.

Resources