Should you use a partial class across projects?

我们两清 提交于 2019-11-27 15:26:11

You can't write a partial class across projects. A partial class is a compile-time-only piece of syntactic sugar - the whole type ends up in a single assembly, i.e. one project.

(Your original DAL file would have to declare the class to be partial as well, by the way.)

I can't answer your question about the best way to organize your layers, but I can try to answer your question about how best to emulate partial classes.

Here are a few thoughts:

  • The first thing that springs to mind is inheritance. It's not necessarily the best solution always, but you may not have a choice since you may need to be able to have your objects be able to be treated like the base class.
  • Composition is also a good choice (that is, wrapping the class in another class). This gives you a little bit nicer decoupling from your DAL, but can be tedious to implement.
  • If you really just need to add a method or two onto an existing class, you might also consider using an extension method, but these can quickly create spaghetti code if you use them too much.

Partial classes have to exist in the same assembly. Otherwise, how would the compiler decide where to merge the partial classes to?

Using Visual Studio 2015 and later it is possible to split partial classes across projects: use shared projects (see also this MSDN blog).

For my situation I required the following:

  • A class library that defines some classes used as interface by several client applications.
  • The client application.
  • A setup application that creates tables in the database.
    Due to limitations of the installer this setup has to be self contained. It cannot reference any assemblies beyond the .NET framework. The setup should insert some enum constants into tables, so ideally it should reference the class library.
    The setup can import a Shared Project.
  • As shared project is similar to copy pasting code, so I want to move as little as possible into the shared project.

The following example demonstrates how partial classes and shared projects allow splitting classes over different projects.

In Class Library, Address.cs:

namespace SharedPartialCodeTryout.DataTypes
{
    public partial class Address
    {
        public Address(string name, int number, Direction dir)
        {
            this.Name = name;
            this.Number = number;
            this.Dir = dir;
        }

        public string Name { get; }
        public int Number { get; }
        public Direction Dir { get; }
    }
}

Class Library is a normal Visual Studio Class Library. It imports the SharedProject, beyond that its .csproj contains nothing special:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
<!-- standard Visual Studio stuff removed -->
    <OutputType>Library</OutputType>
<!-- standard Visual Studio stuff removed -->
  </PropertyGroup>
<!-- standard Visual Studio stuff removed -->
  <ItemGroup>
    <Reference Include="System" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Address.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="..\SharedProject\SharedProject.projitems" Label="Shared" />
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

Address.Direction is implemented in the SharedProject:

namespace SharedPartialCodeTryout.DataTypes
{
    public partial class Address
    {
        public enum Direction
        {
            NORTH,
            EAST,
            SOUTH,
            WEST
        }
    }
}

SharedProject.shproj is:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Label="Globals">
    <ProjectGuid>33b08987-4e14-48cb-ac3a-dacbb7814b0f</ProjectGuid>
    <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
  </PropertyGroup>
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
  <PropertyGroup />
  <Import Project="SharedProject.projitems" Label="Shared" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>

And its .projitems is:

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
    <HasSharedItems>true</HasSharedItems>
    <SharedGUID>33b08987-4e14-48cb-ac3a-dacbb7814b0f</SharedGUID>
  </PropertyGroup>
  <PropertyGroup Label="Configuration">
    <Import_RootNamespace>SharedProject</Import_RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="$(MSBuildThisFileDirectory)Address.Direction.cs" />
  </ItemGroup>
</Project>

The regular client uses Address including Address.Direction:

using SharedPartialCodeTryout.DataTypes;
using System;

namespace SharedPartialCodeTryout.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an Address
            Address op = new Address("Kasper", 5297879, Address.Direction.NORTH);
            // Use it
            Console.WriteLine($"Addr: ({op.Name}, {op.Number}, {op.Dir}");
        }
    }
}

The regular client csproj references the Class Library and not SharedProject:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
    <OutputType>Exe</OutputType>
<!-- Removed standard Visual Studio Exe project stuff -->
  </PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
  <ItemGroup>
    <Reference Include="System" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\SharedPartialCodeTryout.DataTypes\SharedPartialCodeTryout.DataTypes.csproj">
      <Project>{7383254d-bd80-4552-81f8-a723ce384198}</Project>
      <Name>SharedPartialCodeTryout.DataTypes</Name>
    </ProjectReference>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

The DbSetup uses only the enums:

The DbSetup.csproj does not reference Class Library; it only imports SharedProject:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
    <OutputType>Exe</OutputType>
<!-- Removed standard Visual Studio Exe project stuff -->
  <?PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <Import Project="..\SharedProject\SharedProject.projitems" Label="Shared" />
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

To conclude:

Can you split a partial class across projects?

Yes, use Visual Studio's Shared Projects.

Is it a good idea to write a partial class in a separate project (creating a dependency) using the same namespace?

Often not (see the other answers); in some situations and if you know what you are doing it can be handy.

I see no reason why this scheme would not work:

Two files contain storage mechanisms (or some other feature). They specify inheritance but contain no business logic:

  • ProductDataAccess.cs
  • ProductWeb.cs

One file contains the business logic:

  • ProductBusinessLogic.cs

Now create two projects:

  • WebProject contains ProductWeb.cs and ProductBusinessLogic.cs.
  • DataProject contains ProductDataAccess.cs and ProductBusinessLogic.cs

Both projects make use of the same business logic.

I agree with Jon Skeet's answer.

I don't think it would be a good choice to approach an issue like this anyway. There are good design patterns out there already that demonstrate the best way to split your tiers/layers of code, and this is just a little syntactic sugar so that Microsoft could make the WinForms/WebForms designer files separate and prevent people from breaking them.

While I agree with you Neil when it comes to pre-linq development, I also wish I could be able to do this in order to split up bussiness logic from partial classes generated by Linq2SQL designer. For example:

Northind.DAL (prj)
-NorthindDataContext (EntityNamespace set to "Northwind.BLL")
--Product() (Entity, partial class auto-generated)
--Category() (Entity, partial class auto-generated)
--Supplier() (Entity, partial class auto-generated)

Northind.BLL (prj)
-Product() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)
-Category() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)
-Supplier() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)

Unfortunately, we can not do this... actually I'd love to know what the recommended way of splitting up layers/tiers when using LINQ.

No.You cant write partial classes in different projects.Because at a time compiler gets a single project for compilation and so scans for list of classes,methods,fields etc in that project only.So if you have some parts of the partial class in other projects,compiler cant find those.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!