.NET resolves a class to the wrong DLL - c#

My C# project has references to two third party DLLs. This is important because it means I don't have access to source code and can't modify or recompile these two DLLs.
Let's call them dll A and dll B. Here's what dll A looks like:
namespace ThirdParty.Foo
{
public class Bar
{
...snip...
}
public class Something
{
public Bar MyProperty { get; set; }
}
}
And here's what dll B looks like:
namespace ThirdParty.Foo
{
public class Bar
{
...snip...
}
public class SomethingElse
{
public Bar MyProperty { get; set; }
}
}
As you can see, they have the same namespace and they both define a class with the same name. My C# code needs a reference to both DLLs. I use the alias property on the reference to be able to distinguish between the two references and I also extern alias firstDll and extern alias secondDll at the top of my C# file. So far so good.
It seems obvious to me that the type of Something.MyProperty is firstDll.ThirdParty.Foo.Bar and the type of SomethingElse.MyProperty is secondDll.ThirdParty.Foo.Bar but for some reason, Visual Studio gets confused and resolves the type of both properties to the same Bar class in firstDll.
Is there a way for me to "force" VisualStudio to resolve the correct type?
EDIT:
the error I'm getting in Visual Studio is: Cannot implicitly convert type 'ThirdParty.Foo.Bar [d:\MySolution\References\Second.dll]' to 'ThirpParty.Foo.Bar [d:\MySolution\References\First.dll]'

Create a DLL that will serve as a wrapper for DLL A. Let's call the new DLL "C". Your project will then reference DLL B and C.

If the two types have the same name and namespace, then you are pretty much stuck. In C#, the name/identifier is quite important, "best fit" will only work in special situations.
However, you could write wrappers for the two different types, and make those wrappers have different names. By having two different (or even one) project just for the wrapper, you could have only one reference, thus effectively resolving the conflict "by force".

Something that works(for me it did referenced correctly) is the following,first(as you probably already did)click each dll in the references and assign an alias and place the proper extern alias.After to use the class Something and SomethingElse(and properly assign the Bar Property) create one class for each of those classes(Something and SomethingElse)and derive from them and shadow the MyProperty property:
public class TestFirst : first.ThirdParty.Foo.Something
{
//here you shadow and since you must provide the alias
//and the fully qualified name it will bet set to the
//right Bar class,same bellow in testsecond.
public first.ThirdParty.Foo.Bar MyProperty { get; set; }
}
public class TestSecond : second.ThirdParty.Foo.SomethingElse
{
public second.ThirdParty.Foo.Bar MyProperty { get; set; }
}
After its just business as usual:
TestSecond t = new TestSecond();
t.MyProperty = new second.ThirdParty.Foo.Bar();

I would load the dlls explicitly via Assembly.Load then do a createinstance on the types you need then invoke the methods via dynamic - that's because I am lazy.
The other (not lazy) way is to then use reflection to find the method and invoke it.

Since you have an extreme case here where the two assemblies not only have the same namespace, but also the same full assembly name (meaning the types have the same assembly-qualified name), you may want to consider more extreme measures to resolve it. If it's a fully managed DLL (no native code mixed in) and not strong named (or you're okay with removing the strong naming), you may be able to get away with a procedure like this:
Run ildasm and output to a .il file on disk.
Modify the .il file using a careful search and replace to change the root namespace for all types (be cautious for inner namespaces or type names that contain the same text as the root namespace.)
Run the modified file through ilasm to build a new .dll with the changes.

You can use the keyword var instead of specifying the type explicitly to avoid ambiguous references
var x = new ThirdParty.Foo.Something();
var y = new ThirdParty.Foo.SomethingElse();
var barX = x.MyProperty;
var barY = y.MyProperty;

Related

Is it possible to reference existing source files in C# Roslyn Code Generation?

So consider the case where I have a class ClassA inside of the project that is currently being generated into:
public class ClassA
{
public ClassA(int a)
{
A = a;
}
public int A { get; set; }
}
Let's say that I wanted to automatically create an extension method for ClassA, something like:
public static class ClassAExtensions
{
public static ClassA Double(this ClassA classA)
{
return new ClassA(classA.A * 2);
}
}
When trying to create this source code using the new source code generators, the compilation can't seem to find ClassA. I've tried adding the namespace of ClassA into the generated document and setting the namespace of the generated extension method class to the namespace directly to that of ClassA, but neither seem to be able to see it:
The type of namespace 'ClassA' does not exist in the namespace 'ClassANamespace' (are you missing an assembly reference?)
So the final questions are:
Is there some trick to making the code generation compiler be able to see my non-generated code?
Is this even possible right now?
Is there a workaround to get something like this to work?
Many of the samples provided declare the class being modified partial, but I don't particularly like this for what I'm trying to do.
I've also looked into adding an assembly reference, though my understanding was that the code being generated should be included and compiled alongside the existing code. Also, if this code is being compiled before my "production" code, then adding an assembly reference would not be possible and/or this would create a circular reference.
Files added in a source generator act like regular files from the perspective of the rest of the language rules so yes you can absolutely reference classes in the user's code as long as you're qualifying them correctly. It sounds like you have a bug; if there's still a specific problem you may want to try creating a project that contains both the input file and also the source generated output; you should see the same error and then can figure out what's up.

Use Properties of baseclass in referenced assembly [duplicate]

I created a assembly having a child class that derives from a parent defined in another assembly.
When I add reference to the child, Visula studio also requires reference to be added to the parent.
Why is it so and how can I prevent it without losing any functionality?
What you describe is partially possible. You can eliminate the need for them to explicitly reference the hidden assembly, but that assembly will still get pulled in at compiled time, and required at runtime.
Let's say you have these classes defined:
// in assembly 1:
public class A
{
public virtual void Foo() { }
}
// and in assembly 2:
// requires explicit reference to assembly 1 to use
public class B : A
{
public override void Foo() { }
public A Value { get; set; }
public void Foo(A value) { }
}
// has implicit reference to assembly 1, but end user can ignore
public class C
{
private A Value { get; set; }
internal void Foo(A value) { }
protected internal A Bar() { return new A(); }
}
// usable at runtime even if assembly 1 is missing, as long as you don't call Foo()
public class D
{
public void Foo() { A blah = new A(); }
public void Bar() { }
}
If the end user uses class B, they will require an explicit reference to assembly 1. Since A is part of B's public interface, in order to use B, you have to know about A. There are 3 different public references to A, and any of them will require knowing about A to use B.
However, class C makes references to A, but all references are private/internal/local. Since every reference to A is hidden from the outside, the end user doesn't have to explicitly know about assembly 1. It will still be required at runtime, but you don't have to add it as a reference, it's an indirect reference.
And if the end user uses class D, without ever using B or C, assembly 1 will only get loaded if you call D.Foo(), which has a local variable of type A. You can actually use D.Bar() freely even if assembly 1 is completely missing at runtime. Although if you call D.Foo() and assembly 1 is missing, you'll get an exception.
In C/C++, class definition is present in a .h header file. That gives you ability to reference information about a class (as needed e.g. when you want to inherit from that class) without the need to source file with implementation information. The downside is code duplication (implementation in .cpp file needs to repeat most of the information in .h file).
In .NET world the design is different: an assembly contains both the code for the class (CLR bytecode) as well as all the metadata (class name, information about its members etc.) needed to e.g. inherit from that class.
A consequence of that design is that in order to use a class defined in assembly A that inherits from a class in assembly B, .NET needs both A and B assemblies. Or more generically: if you use anything from a given assembly (a class, an enum, a struct), either directly or indirectly, you need to reference that assembly.
I'm not sure what you want to prevent. If you decide to split your code in two assemblies like you described, there's no way around the need to reference both of them.
There are, of course, different ways of structuring your code but not knowing what goal you're trying to achieve by splitting the code into 2 assemblies in the first place, it's impossible to make a useful suggestion.

Returning into object from Assembly.LoadFrom() in C#

I'm trying to make an expansion setup for this game I'm developing, (not going to go into detail about), but all a single expansion will need is the 1 .dll file added into the Expansions folder I have added.
I have figured out how to access these .dll added into this folder as seen below:
Assembly ExpAssembly = Assembly.LoadFrom("Expansions/Intrique.dll");
Type myType = ExpAssembly.GetTypes()[0];
Here is an example of the class I'm trying to load:
public class Expansion: MyGame.Expansion {
public Expansion() {
//Stuff
}
public string SomeMethod()
{
return "Test";
}
}
Calling the following code runs SomeMethod() just fine
MethodInfo Method = myType.GetMethod("SomeMethod");
object myInstance = Activator.CreateInstance(myType);
MessageBox.Show(Method.Invoke(myInstance, null).ToString());
But what I want to do is be able to write Expansion expObj; and assign it by calling new Expansion() from this not-referenced .dll, but not in the library itself.
(For the purposes of this answer, I'm going to assume that your Expansion subclass is has a fully qualified name of Intrique.Expansion. I.e. the namespace is the same as the name of the DLL).
Because your main program does not reference Intrique.dll, the code in your main program cannot use the types in that DLL directly. That is, Intrique.Expansion is not a usable type in the context of the written code of your main program, though it can be used at run-time.
Taking your code example literally, the only approach likely to work given the code you have now would be to use dynamic:
dynamic myInstance = Activator.CreateInstance(myType);
myInstance.SomeMethod();
This is because SomeMethod() is declared only in Intrique.Expansion. There's not any other type you could use statically in your main program where that method is known.
If that method was instead an implementation of a member of some interface that Intrique.Expansion implements and which your main program references, or was an override of some virtual member of MyGame.Expansion (which presumably your main program references, if not actually declares), then you could cast the instance to the interface type or MyGame.Expansion respectively and call the method that way:
ISomeInterface myInstance = (ISomeInterface)Activator.CreateInstance(myType);
myInstance.SomeMethod();
or:
MyGame.Expansion myInstance = (MyGame.Expansion)Activator.CreateInstance(myType);
myInstance.SomeMethod();
Finally, given that you are trying to implement some kind of extensibility architecture, you might consider using the Managed Extensibility Framework, which is designed specifically to handle a lot of the messy parts of exactly this kind of thing.

Members which are only public from another assembly

In C# we can define any member as Internal, which makes it only visible inside the current assembly:
internal int Age;
I was wondering if its possible to reverse this effect, marking it private/protected to this assembly, but public to a specified other assembly.
This sounds completely insane, but we have a valid reason to do this. We're using the Unity3D game engine, where all of our game-logic is in the 'runtime' assembly. We can also define custom editors for these classes, which allow us to create custom UI controls in the IDE. Those editors live in a special 'editor' assembly.
This editor assembly frequently needs more information about a specific type in the runtime assembly then we'd like to expose to our own assembly. Our current solution is to get the specific private/protected member via Reflection, but i'd like to know if there is a better solution.
You can't change the visibility of these members.
One option is to create an interface that exposes the desired members, and then explicitly implement it:
class MyClass : IEditable
{
internal int Age { get; private set; }
int IEditable.Age { get; set; }
}
You'd have to cast MyClass to IEditable to access the properties in this case. It would also help identify when changing the runtime assembly would break the editor.
It does sound like a design issue. The data that must be known to both assemblies should be isolated to its own assembly and referenced by each of them. Failing that, you could look at creating a wrapper/adapter that publicly exposes the hidden data in the core assembly, in a read-only way that is available to your other assemblies.

Mixing generic methods and extension methods

I created the Class1.GetChild<T>() where T : DependencyObject extension method in lib1.dll assembly. After that, all assemblies that depends on lib1.dll failed to compile with error:
The type 'System.Windows.DependencyObject' is defined in an assemebly
that is not referenced. You must add a reference to assembly
'WindowsBase' etc...
Why dependent assemblies requires WindowsBase even if they don't use GetChild?
.
To reproduce (vs2010 .net4):
lib1.dll (references WindowsBase)
namespace lib1
{
public static class Class1
{
public static T GetChild<T>(this DependencyObject src) where T : DependencyObject
{
return default(T);
}
}
public static class Class2
{
public static int SomeExtMethod(this string src)
{
return 0;
}
}
}
lib2.dll (references lib1 but not WindowsBase)
using lib1;
class someClass
{
void someFct()
{
"foo".SomeExtMethod(); // error: The type 'System.Windows.DependencyObject'
// is defined in an assemebly that is not referenced.
// You must add a reference to assembly 'WindowsBase' etc..
}
}
.
Update:
I think there's definitly something when mixing generic methods and extension methods. I tried to demonstrate the issue in the following sample:
// lib0.dll
namespace lib0
{
public class Class0 { }
}
// lib1.dll
using lib0;
namespace lib1
{
public static class Class1
{
public static void methodA<T>() where T : Class0 { } // A
public static void methodB(Class0 e) { } // B
public static void methodC(this int src) { } // C
}
public static class Class2
{
public static void methodD(this String s) { }
}
}
// lib2.dll
using lib1;
class someClass
{
void someFct()
{
Class2.methodD(""); // always compile successfully
"".methodD(); // raise the 'must add reference to lib0' error depending on config. see details below.
}
}
A, //B, //C -> compile ok
A, B, //C -> compile ok
//A, B, C -> compile ok
A, //B, C -> raise error
A, B, C -> raise error
//A means methodA is commented. As Damien pointed out, type inference might play some role. Still curious to know the ins and outs.
Your situation has been answered by Microsoft here:
https://connect.microsoft.com/VisualStudio/feedback/details/668498/problem-with-extension-method-in-c-compiler
There are other use-cases as well independent of extension methods which produce this error wrongly.
Consider this:
Define a generic method in a type, say TP1, defined in library say LB1.
Type constrain the generic method on some type defined in some other library LB2.
Define another method in TP1.
Now in your library reference only LB1 and try to call the second method of type TP1
If you don't use TP1 but some other type defined in LB1, you do not get the error.
Also, even if one of the method of type TP1 expects a parameter of the type defined in LB2 (and you do not call this method) it does not produce this error
When one assembly depends on another assembly, the first assembly also depends on all the dependencies of the other--regardless of what is used. Assembly dependencies are effectively decoupled, another version of either assembly can be deployed after compilation, the compiler can't know that under circumstances like this one or more of the dependencies in the second assembly won't be used by the first assembly.
To solve the issue you can simply add a reference to WindowsBase.
Or, as prashanth points out, put the SomeExtMethod into a different assembly so code that uses that doesn't need to take a dependency on WindowsBase.
Update:
If you don't use anything from an assembly, you don't need any of its dependencies. But, as soon as you use one assembly, you need all the dependencies of that assembly as well. This is apparent in the way Visual Studio add references. If you add a reference to an assembly, it will copy all the dependent assemblies (not registered in the GAC) into your debug/release directories along with the assembly you added.
Update:
As to the compile error: that's the way it was written--there may be no other reason. Is it a good idea to get a compile error if you don't reference dependent assemblies? Maybe, you're likely to use something from a reference and that might use something directly from the references references--better a compile error than a deployment error.
Why not a compile error on every non-referenced secondary dependency? Again, it was written that way. Maybe an error here too would be good; but that would be a breaking change and would require really persuasive reasons.
I'm not sure this can be answered by anyone other than someone on the compiler team. I'm now thinking that it's to do with type inference - but whereas §7.6.5.1 Method Invocations talks about inference, §7.6.5.2 Extension method invocations is silent on the matter - despite the fact that inference obviously does take place when searching for applicable extension methods.
I think it's attempting some form of inference before it's performing the comparison on identifiers (which would immediately rule out the extension method since it's got the wrong name). Obviously, it can't perform any form of inference for this type if it's unable to understand the type constraints.
Hence, when you change your type constraint to just class, it now successfully passes over this method - it can infer a type parameter, but it now eliminates this extension method successfully.
When you reference another assembly, I assume the compiler needs to be able to parse any method signatures defined in that assembly, so it knows where to go to find that function if it sees a call to it.
If you replace your GetChild() function with
public static T GetChild<T>(this T src)
{
if (typeof(T) == typeof(DependencyObject)) return default(T);
else return default(T);
}
or something similar to that, it does not require you to include the reference to WindowsBase that you're running into. But if you add where T : DependencyObject to the signature, it does require it.
Effectively, you can use whatever assembly references you want in a project, so long as you don't expose them in any way. Once you expose them, then every other project which uses your library needs to be able to handle them, and thus requires those references themselves.
Maybe ILMerge would solve this problem. The idea is you create 2 dlls and merge them into one. That way you can have a single dll but reference it twice. Then way you can separate the GUI code from other code and only add the reference that you need to the particular project.
The answer is simple. It is because the method is decalre as public. This mean that it is visible to lib2.dll (in your case.) In other word you can call this method.
It also has a constrain that only classes inherited from DependencyObject can call this method. So that is the reason why you need to reference 'WindowsBase'.

Categories

Resources