1

If I use VS2015.1 to create a new sample project (either WebForms or MVC), two files are created for configuring OWIN:

\Startup.cs (or .vb)

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(WebApplication6.Startup))]
namespace WebApplication6
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

\App_Start\Config.Auth.cs (or .vb)

namespace WebApplication6
{
    public partial class Startup {

        public void ConfigureAuth(IAppBuilder app)
        {
           // removed for brevity
        }
    }
}

I see that both classes are declared as partial, but in the many examples online of how to use OWIN, the classes are not partial (see here, here, here and here).

Could anyone please explain if there is a correct or best approach, and what difference it makes to the application whether partial is used or not?

Community
  • 1
  • 1
EvilDr
  • 7,561
  • 10
  • 60
  • 114

2 Answers2

3

The accepted answer is true if and only if the code generator is generating the file each and every time a build happens. The example with OWIN does not qualify since both files are generated only once when the framework / scaffolding choices are made.

Therefore the only reason I can see that the startup is generated as a partial class is that the framework developers did not want to couple the generation of the owin authorization (a cross cutting concern) with the generation of the startup scaffolding; however, they were only successful in removing the clutter from the base startup.cs scaffolding and were not able to decouple it since they had to introduce the OwinStartupAttribute to the base start up and make a call to the method introduced in the new partial class ConfigureAuth. This is actually a perfect example of how not to use a partial class. Partial class definitions should be decoupled otherwise the benefit gained by using partial class is outweighed by the indirection it creates. Having to modify the base partial class definition to add another partial class to add the OWIN authorization makes it clear to me that this is a flawed approach.

1

I think I found an answer here, but would still appreciate anything others can add in the context of OWIN specifically:

https://stackoverflow.com/a/3601918/792888

The biggest use of partial classes is make life easier on code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns.

So the partial class is simply compiled into a class. The partial declaration allows other classes with the same name to co-exist (which are then all compiled together into a single class).

Community
  • 1
  • 1
EvilDr
  • 7,561
  • 10
  • 60
  • 114