1

I have an ASP.NET Web API project hosted in a Windows Service, using OWIN. I'm using a Startup class that configures some things, and am using the IAppBuilder.UseWebApi() option. Everything works perfectly in the debugger and from the command line (I use a command line argument of -e to run in console, or it can run as a Windows Service).

Everything is working great, BUT, when I build in Release mode with the build option enabled for "Optimize Code", my service controllers don't seem to work.

I have my controller in a separate class library, and I'm using this line to probe the controller on application start, as suggested here: Self-hosting WebAPI application referencing controller from different assembly

var controllerType = typeof(MetricsController);

I have a feeling that the Optimize Code option causes the compiler to ignore this line. Does anyone have any insight or ideas about how I can make this work?

Thanks!

Community
  • 1
  • 1
trnelson
  • 2,715
  • 2
  • 24
  • 40
  • 1
    Have you tried turning off code optimization when you compile? Did everything work as expected when you did that? – Adam Zuckerman Mar 27 '14 at 23:28
  • @AdamZuckerman I did actually. When I turn off Code Optimization, it works as expected. I don't know much about Code Optimization; do you know if it's worth disabling to fix this issue? Or maybe there's a way to have the optimization ignore this line somehow? I'll do some more looking. Thanks for your comment! – trnelson Mar 28 '14 at 02:06

1 Answers1

1

After working with this for a bit, I implemented the following approach which the Optimize Code option seems to be happy with.

Class-level member:

private readonly List<Type> _controllers = new List<Type>();

Then in my Startup.Configuration method, I replaced this:

// Hack: This forces a manual probe of the controller assembly
var controllerType = typeof(MyController);

With this:

// Better Hack: This forces a manual probe of the controller assembly
_controllers.Add(typeof(MyController));

What seems to be happening is that the Optimize Code option is stripping out logic that is declared but never used. In this case, I was using the original hack to probe the assembly so the application knows about its existence. Since it was so tightly scoped and the variable controllerType was never used, the compiler ignores it. The new approach is probably just enough of a hint that it may be used that the compiler keeps it.

I tried a reflection-based approach but could not get it to work. I even manually loaded the assembly having the controllers, and I could see it loaded in the AppDomain when debugging, but for some reason it still wouldn't work. I could even verify that the List was populated with the controller types, but strangely no luck. Definitely open to any suggestions on this since I will be using a similar approach in the future on another project.

trnelson
  • 2,715
  • 2
  • 24
  • 40