I have a class with a default constructor. Based on an assembly
attribute I'm trying to change the default constructor with additional
arguments. The type of the arguments I'm adding is located in a
different assembly.
When I've change the assembly and try to save it I get an exception,
which I cannot seem to fix: Member 'OtherAssembly.IViewModel' is
declared in another module and needs to be imported.

The assembly that contains the Type is referenced by the assembly I'm
changing. I also see this in the AssemblyReferences in the current
module. I'm importing the Type into the current module when I get the
TypeReference out of the Attribute.

It is probably someting simple but I can't seem to find it. What Am I
doing wrong?
Thanks for your help!

Below the code I'm using to test the issue.
Assembly "Views.dll" I'm changing contains:

public class Class1
{
        public Class1() { }
}

[assembly: OtherAssembly.ViewModel(typeof(Class1),
typeof(OtherAssembly.IViewModel))]


The "OtherAssembly" I'm referencing contains:

namespace OtherAssembly
{
        public interface IViewModel { }

        [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
        public class ViewModelAttribute : Attribute
        {
                public ViewModelAttribute(Type viewType, Type viewModelType) { }
        }
}

The Code I'm using in a separate tool to change the assembly:

var module = ModuleDefinition.ReadModule("Views.dll");

//load Assembly attribute
var attribute = module.Assembly.CustomAttributes.First(a =>
a.Constructor.DeclaringType.FullName ==
"OtherAssembly.ViewModelAttribute");
var customAttributeArguments = attribute.ConstructorArguments;

//get Arguments from the attribute
var viewType =
module.Import((TypeReference)customAttributeArguments[0].Value).Resolve(); //
Resolves Class1
var viewModelType =
module.Import((TypeReference)customAttributeArguments[1].Value).Resolve(); //
Resolves OtherAssembly.IViewModel

//find the constructor of "Class1"
var ctor = viewType.Methods.First(m => m.IsConstructor && !m.IsStatic
&& m.Parameters.Count == 0);

//add "OtherAssembly.IViewModel" parameter to constructor
var viewModelTypeParameter = new ParameterDefinition(viewModelType);
ctor.Parameters.Add(viewModelTypeParameter);

//write causes exception: Member 'OtherAssembly.IViewModel' is
declared in another module and needs to be imported
module.Write("Views2.dll");

-- 
--
mono-cecil

Reply via email to