phaedo phaedo - 3 months ago 19
C# Question

wcf CS0012 puzzle with nested type

Sorry if this is obvious but I am pulling my hair over this issue: I have a class library ClassLibrary1 that defines

Class1
, and a WCF Service Library WcfServiceLibrary1 referencing ClassLibrary1 that defines a class
Response
in which Class1 is nested:

public class Response
{
public string Message { get; set; }
public Class1 Value { get; set; }
}


Then I added a simple console application as client referencing WcfServiceLibrary1 (but not ClassLibrary1, to simulate separation between business logic and client logic). However I cannot compile WcfServiceLibrary1 as I get error "CS0012 The type 'Class1' is defined in an assembly that is not referenced. You must add a reference to assembly 'ClassLibrary1..."

What am I missing? Thanks

Class1.cs:

namespace ClassLibrary1
{
public class Class1
{
public int SomeInt { get; set; }
}
}


IService1.cs:

namespace WcfServiceLibrary1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
Response ConvertToClass(int value);

[OperationContract]
Class1 AltConvertToClass(int value);
}

public class Response
{
public string Message { get; set; }
public Class1 Value { get; set; }
}
}


Service1.cs:

namespace WcfServiceLibrary1
{
public class Service1 : IService1
{
public Response ConvertToClass(int value)
{
return new Response() {Message = "Success", Value = new Class1() {SomeInt = value}};
}

public Class1 AltConvertToClass(int value)
{
return new Class1() {SomeInt = value};
}
}
}


Program.cs:

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var client = new ServiceReference1.Service1Client();
client.Open();

Console.Write("Enter number:");
var s = Console.ReadLine();

var n = int.Parse(s);

var c = client.ConvertToClass(n);
Console.WriteLine($"Result: Message = {c.Message}, Value = {c.Value}"); //CS0012
var c2 = client.AltConvertToClass(n);
Console.WriteLine($"Result: {c2.SomeInt}");

Console.WriteLine("\nPress enter...");
Console.ReadLine();
}
}
}

Answer

This error comes from ConsoleApplication1 (the client) referencing WcfServiceLibrary1 (the host), causing the automatically generated service code in [ConsoleApplication1 -> Service References -> ServiceReference1 -> Reference.svcmap -> Reference.cs] to reuse WcfServiceLibrary1.Response (which relies on ClassLibrary1.Class1 whence CS0012) yet otherwise creates ServiceReference1.Class1 to deal with the AltConvertToClass method.

The solution is to remove the reference from ConsoleApplication1 (the client) to WcfServiceLibrary1 (the host), which makes perfect sense since the two assemblies will typically be run on separate machines.

Thanks everyone for your contributions!