Activator.CreateInstance and Generic method in C# - c#-4.0

interface IExecutor
{
void Execute();
}
class Executor2<T> where T : IExecutor
{
public void Execute()
{
var ex = (T)Activator.CreateInstance(typeof(T));
ex.Execute();
}
}
It was a question at an interview. They told me that sometimes this code falls (causes exceptions) and there are at least 3 reasons that could cause the problems. It's unknown what exceptions were there. But the method Execute was created good, its implementation has no fault.
Does anybody have a suggestion about that?
Edit: There are at least 3 reasons that could cause the problems. What are these reasons?

On the face of it I can see a few issues.
The code doesn't compile, but I can ignore that and make it compile.
The code doesn't do what you think it does.
To explain 2: you specify a type T at the class definition with a constraint on IExecutor, but you then define another type T at the method level without a constraint. This doesn't compile.
If I fix this and remove the <T> definition from the method I can see a number of reasons for it failing without much warning:
ex is null.
Type T doesn't have a public parameterless constructor defined.
Perhaps it cannot load the DLL containing T.
As spotted by Jakub:
T could be an interface (no constructor).
T could be an abstract class, these don't allow instances to be created directly.
The first can be guarded against using a null check if (ex != null) and the second can be guarded against using another generic constraint new():
class Executor2<T> where T : IExecutor, new()
{
}
Obviously you could also amend your code to including exception logging. This might be useful in figuring out what the actual problems are instead of just stabbing in the dark:
public void Execute<T>()
{
try
{
var ex = (T)Activator.CreateInstance(typeof(T));
ex.Execute();
}
catch (Exception ex)
{
Log(ex); // Mystical logging framework.
throw;
}
}
This is the only answer I can cobble together considering I didn't understand the question.
If I were asked this in an interview I'd likely say I couldn't name all 3, but I'd know how to change the code to be more maintainable and tell me what was wrong. Then I'd likely walk for asking pointless interview questions.

T may be an interface or abstract class - and you cannot create instances of them, or T doesn't have a parameterless constructor.
Also, var ex = (T)Activator.CreateInstance(typeof(T)); could be rewritten as var ex = Activator.CreateInstance<T>();

Is it assumed that there is no fault in T's design? By which I mean, if T defines a static constructor which does Bad Stuff, type initialisation for T will fail giving a different exception to that which would occur if it did not have a parameterless constructor.
For that matter, if T defines a parameterless constructor which will fail then it's also broken.
Also, if the type has a private constructor you will get an error. Or if the type inherits from a type which will cause a TypeInitialisationException
[Edit]
Try this:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try {
new Executor2<IExecutor>().Execute();
}
catch { Console.WriteLine("Failed IExecutor"); }
try { new Executor2<AbstractExecutorWithImpl>().Execute(); }
catch { Console.WriteLine("Failed AbstractExecutorWithImpl"); }
try { new Executor2<AbstractExecutorWithNoImpl>().Execute(); }
catch { Console.WriteLine("Failed AbstractExecutorWithNoImpl"); }
try { new Executor2<ConcreteExecutor>().Execute(); }
catch { Console.WriteLine("Failed ConcreteExecutor"); }
try { new Executor2<DerivedExecutor>().Execute(); }
catch { Console.WriteLine("Failed DerivedExecutor"); }
try { new Executor2<DerivedExecutorWithBadConstr>().Execute(); }
catch { Console.WriteLine("Failed DerivedExecutorWithBadConstr"); }
try { new Executor2<DerivedExecutorWithPrivateConstr>().Execute(); }
catch { Console.WriteLine("Failed DerivedExecutorWithPrivateConstr"); }
try { new Executor2<DerivedExecutorWithPublicBadConstr>().Execute(); }
catch { Console.WriteLine("Failed DerivedExecutorWithPublicBadConstr"); }
Console.ReadLine();
}
}
interface IExecutor
{
void Execute();
}
abstract class AbstractExecutorWithImpl : IExecutor
{
public void Execute()
{
Console.Write("Executing AbstractExecutorWithImpl ");
}
}
abstract class AbstractExecutorWithNoImpl : IExecutor
{
public abstract void Execute();
}
class ConcreteExecutor : IExecutor
{
public void Execute()
{
Console.WriteLine("Executing ConcreteExecutor");
}
}
class DerivedExecutor : AbstractExecutorWithNoImpl
{
public override void Execute()
{
Console.WriteLine("Executing DerivedExecutor");
}
}
class DerivedExecutorWithBadConstr : IExecutor
{
static DerivedExecutorWithBadConstr() { throw new Exception("Static initialisation Exception"); }
public void Execute()
{
Console.WriteLine("Executing DerivedExecutorWithBadConstr");
}
}
class DerivedExecutorWithPrivateConstr : DerivedExecutor
{
private DerivedExecutorWithPrivateConstr() { }
}
class DerivedExecutorWithPublicBadConstr : DerivedExecutorWithBadConstr
{
public DerivedExecutorWithPublicBadConstr() : base() { }
}
class Executor2<T> where T : IExecutor
{
public void Execute()
{
var ex = (T)Activator.CreateInstance(typeof(T));
ex.Execute();
}
}
}

Related

ninject interception with attribute

I'm trying to use ninject interception in my project for logging exceptions. On the line
public override void Load()
{
this.Bind<IPoShippingRepository>().To<PoShippingRepository>().Intercept().With<ExceptionInterceptor>();
}
I have got an error:
Error loading Ninject component IAdviceFactory
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
Ninject initializing is simple:
private static IKernel _kernel;
public UnitOfWork()
{
_kernel = new StandardKernel(new DomainNinjectModule());
}
...
public class DomainNinjectModule : NinjectModule
{
public override void Load()
{
this.Bind<IPoShippingRepository>().To<PoShippingRepository>().Intercept().With<ExceptionInterceptor>();
}
}
class ExceptionInterceptor : IInterceptor
{
private eKindOfLog _kindOfLog;
public ExceptionInterceptor(eKindOfLog kindOfLog)
{
_kindOfLog = kindOfLog;
}
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch (Exception ex)
{
switch (_kindOfLog)
{
case eKindOfLog.Sql:
SimpleLog.LogSqlError(ex);
break;
case eKindOfLog.Error:
SimpleLog.LogSqlError(ex);
break;
}
}
}
}
I installed Ninject.dll, Ninject.Extensions.Interception.dll and Ninject.Extensions.Interception.DynamicProxy.dll.
Method where I used interception attribute is public and virtual.
Please, help what have I done wrong?

Re-write java anonymous class in groovy style closure?

I am a Java programmer trying to learn groovy. Closures are a bit confusing for me at the moment.
Could I have some help to understand how I can use a closure to replace the abstract code I have below. I'm thinking a function defined as a variable or something like that however I can't crack it yet.
//MY ABSTRACT CLASS
public abstract class AbstractResource {
protected StreamingOutput activityStreamingOutput(serviceResponse){
return new StreamingOutput() {
#Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
def writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write(serviceResponse);
writer.flush();
}
}
}
}
// MY CHILD CLASS
class MaintanenceResourceImpl extends AbstractResource{
public void doSomething(Reader reader) throws Exception {
// I'D LIKE TO DO SOMETHING GROOVYISH HERE
def StreamingOutput = activityStreamingOutput(serviceResponse)
}
thanks
There's not much you can do here (w/o knowing other details), but this:
abstract class AbstractResource {
Closure activityStreamingOutput(serviceResponse){
{ OutputStream os ->
os.withWriter{ it << serviceResponse }
}
}
}
class MaintanenceResourceImpl extends AbstractResource {
void doSomething(Reader reader) throws Exception {
activityStreamingOutput(serviceResponse).call someOutputStream
}

How is IClock resolved with SystemClock in this example?

I am trying to learn IOC principle from this screencast
Inversion of Control from First Principles - Top Gear Style
I tried do as per screencast but i get an error while AutomaticFactory try create an object of AutoCue. AutoCue class has contructor which takes IClock and not SystemClock. But my question is , in screencast IClock is resolved with SystemClock while inside AutomaticFactory .But in my code , IClock does not get resolved . Am i missing something ?
class Program
{
static void Main(string[] args)
{
//var clarkson = new Clarkson(new AutoCue(new SystemClock()), new Megaphone());
//var clarkson = ClarksonFactory.SpawnOne();
var clarkson = (Clarkson)AutomaticFactory.GetOne(typeof(Clarkson));
clarkson.SaySomething();
Console.Read();
}
}
public class AutomaticFactory
{
public static object GetOne(Type type)
{
var constructor = type.GetConstructors().Single();
var parameters = constructor.GetParameters();
if (!parameters.Any()) return Activator.CreateInstance(type);
var args = new List<object>();
foreach(var parameter in parameters)
{
var arg = GetOne(parameter.ParameterType);
args.Add(arg);
}
var result = Activator.CreateInstance(type, args.ToArray());
return result;
}
}
public class Clarkson
{
private readonly AutoCue _autocue;
private readonly Megaphone _megaphone;
public Clarkson(AutoCue autocue,Megaphone megaphone)
{
_autocue = autocue;
_megaphone =megaphone;
}
public void SaySomething()
{
var message = _autocue.GetCue();
_megaphone.Shout(message);
}
}
public class Megaphone
{
public void Shout(string message)
{
Console.WriteLine(message);
}
}
public interface IClock
{
DateTime Now { get; }
}
public class SystemClock : IClock
{
public DateTime Now { get { return DateTime.Now; } }
}
public class AutoCue
{
private readonly IClock _clock;
public AutoCue(IClock clock)
{
_clock = clock;
}
public string GetCue()
{
DateTime now = _clock.Now;
if (now.DayOfWeek == DayOfWeek.Sunday)
{
return "Its a sunday!";
}
else
{
return "I have to work!";
}
}
}
What you basically implemented is a small IoC container that is able to auto-wire object graphs. But your implementation is only able to create object graphs of concrete objects. This makes your code violate the Dependency Inversion Principle.
What's missing from the implementation is some sort of Register method that tells your AutomaticFactory that when confronted with an abstraction, it should resolve the registered implementation. That could look as follows:
private static readonly Dictionary<Type, Type> registrations =
new Dictionary<Type, Type>();
public static void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
registrations.Add(typeof(TService), typeof(TImplementation));
}
No you will have to do an adjustment to the GetOne method as well. You can add the following code at the start of the GetOne method:
if (registrations.ContainsKey(type))
{
type = registrations[type];
}
That will ensure that if the supplied type is registered in the AutomaticFactory as TService, the mapped TImplementation will be used and the factory will continue using this implementation as the type to build up.
This does mean however that you now have to explicitly register the mapping between IClock and SystemClock (which is a quite natural thing to do if you're working with an IoC container). You must make this mapping before the first instance is resolved from the AutomaticFactory. So you should add the following line to to the beginning of the Main method:
AutomaticFactory.Register<IClock, SystemClock>();

Generic InArgument throws an exception trying to get the value

I have an Activity where I declared a InArgument without a type (because I want to know the type of the Expression at design time).
When I execute the activity I get this error in var contentTelegram line:
"The argument of type '<type>' cannot be used. Make sure that it is declared on an activity."
Here is my code:
public InArgument Content { get; set; }
protected override PlcMessage Execute(CodeActivityContext context)
{
try
{
var contentTelegram = Content.Get(context);
return new PlcMessage();
}
catch (Exception ex)
{
throw;
}
}
Here is what I did:
The workflow runtime needs to know about the used types in arguments, so the cacheMetadata is the key to make it work, CacheMetadata uses reflection to know about arguments, notice that only works for simple cases.
public sealed class MyActivity: CodeActivity
{
private RuntimeArgument outMyRuntimeArgument;
// Define an activity input argument of type string
public OutArgument MyUntypedArgument { get; set; }
protected override void CacheMetadata(CodeActivityMetadata metadata)
{
outMyArgument= new RuntimeArgument("MyUntypedArgument", MyUntypedArgument.ArgumentType, ArgumentDirection.Out);
metadata.Bind(MyUntypedArgument, outArgument);
metadata.AddArgument(outMyArgument);
}
protected override void Execute(CodeActivityContext context)
{
context.SetValue(outMyRuntimeArgument, Activator.CreateInstance(Type));
}
}

Strategy Pattern or Interface?

I'm looking to abstract a helper method. The method needs to be able to take in an object, do things with it depending on the type of object, and return a value. Would it be better to do something like this:
interface ICanDo
{
string DoSomething();
}
string DoThings(ICanDo mything)
{
return mything.DoSomething();
}
Or is it better to do something like this:
interface IStrategy
{
string DoSomething(object o);
}
string DoThings(object mything, IStrategy strategy)
{
return strategy.DoSomething(mything);
}
Is the latter even using a strategy pattern, since the strategy isn't being built into the class?
Is there a better way to do this I'm not thinking of? Would it be better to build the strategy into the class, using a wrapper for any class that needs to have DoThings run on it?
Sorry--I'm new to this pattern and trying to figure out where and how to use it best.
This is what I ended up putting together. I'm unsure if this follows good development principles.
class IndexWrapper
{
public interface IDocumentable
{
Document BuildDocument();
}
public interface IDocumentBuilder
{
Type SupportedType { get; }
Document BuildDocument(object o);
}
public class StringDocumentBuilder : IDocumentBuilder
{
public Type SupportedType { get { return typeof(string); } }
public Document BuildDocument(object o)
{
Document doc = new Document();
doc.Add(new Field("string", o as string, Field.Store.YES, Field.Index.ANALYZED));
return doc;
}
}
public static class IndexableFactory
{
public static IDocumentable GetIndexableObject(object o)
{
return GetIndexableObject(o, DocumentBuilderFactory.GetBuilder(o));
}
public static IDocumentable GetIndexableObject(object o, IDocumentBuilder builder)
{
return new IndexableObject(o, builder);
}
}
public static class DocumentBuilderFactory
{
private static List<IDocumentBuilder> _builders = new List<IDocumentBuilder>();
public static IDocumentBuilder GetBuilder(object o)
{
if (_builders.Count == 0)
{
_builders = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => typeof(IDocumentBuilder).IsAssignableFrom(type) && type.IsClass)
.Select(type => Activator.CreateInstance(type))
.Cast<IDocumentBuilder>()
.ToList();
}
return _builders.Where(builder => builder.SupportedType.IsAssignableFrom(o.GetType())).FirstOrDefault();
}
}
private class IndexableObject : IDocumentable
{
object _o;
IDocumentBuilder _builder;
public IndexableObject(object o) : this(o, DocumentBuilderFactory.GetBuilder(o)) { }
public IndexableObject(object o, IDocumentBuilder builder)
{
_o = o;
_builder = builder;
}
virtual public Document BuildDocument()
{
return _builder.BuildDocument(_o);
}
}
}
When in doubt, keep the KISS mantra in your mind - Keep It Short and Simple. Patterns can be very useful, but often they're only useful in specific cases and add unnecessary complexity otherwise.
In my experience, the strategy pattern is useful for when you have multiple different backends to choose from for a class. For example, say you have a logging class that your program uses to print debug information. Maybe in some cases, you want to log to a file. Maybe you'd like to log to a console. Perhaps you'd even like to log to a remote server with a proprietary protocol you company made!
So, your logging class may look like this:
interface IOutputWriter
{
void WriteLn(string message);
}
class ConsoleWriter : IOutputWriter
{
public ConsoleWriter()
{
}
public void WriteLn(string message)
{
Console.WriteLine(message);
}
}
class NetworkWriter : IOutputWriter
{
public NetworkWriter()
{
}
public void WriteLn(string message)
{
//Crazy propietary server protocol action
}
}
class Logger
{
IOutputWriter writer;
public Logger(IOutputWriter writer)
{
this.writer = writer;
}
public void Log(string message)
{
writer.WriteLn(message + "Date");
}
}
With the end result that your program code looks like this:
class Program
{
static void Main(string[] args)
{
Logger logger = new Logger(new ConsoleWriter());
logger.Log("Test");
}
}
The benefit is that if you want to use your crazy networking protocol, you can do it without even looking at the logging class. You just have to make a new class with your IOutputWriter interface and tell your logger to use your custom backend. The strategy pattern is essentially defining reusable interfaces and then using those interfaces to decouple algorithms from each other.

Resources