ASP.NET Web API Unit Test Autofac Module with BuildManager.GetReferencedAssemblies() The 2019 Stack Overflow Developer Survey Results Are In Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceUsing IoC for Unit TestingHow should I unit test threaded code?Unit Testing C CodeIs Unit Testing worth the effort?What is a reasonable code coverage % for unit tests (and why)?Unit test naming best practicesJavaScript unit test tools for TDDWhat is Unit test, Integration Test, Smoke test, Regression Test?WCF vs ASP.NET Web APIHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?How to secure an ASP.NET Web API

Can we generate random numbers using irrational numbers like π and e?

One-dimensional Japanese puzzle

What's the point in a preamp?

Sort list of array linked objects by keys and values

Python - Fishing Simulator

Drawing vertical/oblique lines in Metrical tree (tikz-qtree, tipa)

Simulating Exploding Dice

Can the Right Ascension and Argument of Perigee of a spacecraft's orbit keep varying by themselves with time?

Does Parliament hold absolute power in the UK?

How to handle characters who are more educated than the author?

Do ℕ, mathbbN, BbbN, symbbN effectively differ, and is there a "canonical" specification of the naturals?

Would an alien lifeform be able to achieve space travel if lacking in vision?

What information about me do stores get via my credit card?

What other Star Trek series did the main TNG cast show up in?

different output for groups and groups USERNAME after adding a username to a group

Single author papers against my advisor's will?

Intergalactic human space ship encounters another ship, character gets shunted off beyond known universe, reality starts collapsing

Can withdrawing asylum be illegal?

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

How did passengers keep warm on sail ships?

Can each chord in a progression create its own key?

Why not take a picture of a closer black hole?

Make it rain characters

What is the padding with red substance inside of steak packaging?



ASP.NET Web API Unit Test Autofac Module with BuildManager.GetReferencedAssemblies()



The 2019 Stack Overflow Developer Survey Results Are In
Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceUsing IoC for Unit TestingHow should I unit test threaded code?Unit Testing C CodeIs Unit Testing worth the effort?What is a reasonable code coverage % for unit tests (and why)?Unit test naming best practicesJavaScript unit test tools for TDDWhat is Unit test, Integration Test, Smoke test, Regression Test?WCF vs ASP.NET Web APIHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?How to secure an ASP.NET Web API



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Working on a project in ASP.NET Web API 2 which has Autofac as my IoC container. This project is hosted on IIS and in my Autofac module I use the following method to scan for assemblies:



var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


Why?



https://docs.autofac.org/en/latest/register/scanning.html#iis-hosted-web-applications



But now we are making Unit Tests using NUnit, during my setup I register my module which uses this method. Now I receive the following exception when running my tests:



System.InvalidOperationException: 'This method cannot be called during the application's pre-start initialization phase.'


I understand why I have this exception but I don't have a clue how to make my code work in tests and for deployment environments.



Setup method of NUnit:



[TestFixture]
public abstract class ApplicationTestBase

[SetUp]
public override void Init()

var builder = new ContainerBuilder();

// If the class requires auto mapper mapping, initialize them
// We do this in order not to init them for every test => optimalisation!
if (GetType().GetCustomAttributes<RequiresAutoMapperMappingsAttribute>(false) != null)

builder.RegisterModule<AutoMapperModule>();


this.Container = builder.Build();




Do I need to create a new module specific for my Unit tests or is there another way for this?



AutoMapperTest



[RequiresAutoMapperMappings]
[TestFixture]
public class AutoMapperTests : ApplicationTestBase

[Test]
public void Assert_Valid_Mappings()

Mapper.AssertConfigurationIsValid();




UPDATE



Like Cyril mentioned: Why do you need Ioc in your unit tests? I went searching and indeed you don't have to use the Ioc in your tests. So I ditched the Ioc and initialized my mapper configuration byy doing:



 Mapper.Initialize(configuration => 

var asm = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.StartsWith("ProjectWebService."));

configuration.AddProfiles(asm);
);









share|improve this question
























  • What are you testing ? why do you need IoC in your test ? See stackoverflow.com/questions/1465849/using-ioc-for-unit-testing

    – Cyril Durand
    Mar 8 at 14:36











  • See my update, I have create a test to check if my AutoMapper configuration is valid. Therefore I need to register my AutoMapper profiles and configuration, which is done in the AutoMapper Module.

    – Mivaweb
    Mar 8 at 19:27

















0















Working on a project in ASP.NET Web API 2 which has Autofac as my IoC container. This project is hosted on IIS and in my Autofac module I use the following method to scan for assemblies:



var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


Why?



https://docs.autofac.org/en/latest/register/scanning.html#iis-hosted-web-applications



But now we are making Unit Tests using NUnit, during my setup I register my module which uses this method. Now I receive the following exception when running my tests:



System.InvalidOperationException: 'This method cannot be called during the application's pre-start initialization phase.'


I understand why I have this exception but I don't have a clue how to make my code work in tests and for deployment environments.



Setup method of NUnit:



[TestFixture]
public abstract class ApplicationTestBase

[SetUp]
public override void Init()

var builder = new ContainerBuilder();

// If the class requires auto mapper mapping, initialize them
// We do this in order not to init them for every test => optimalisation!
if (GetType().GetCustomAttributes<RequiresAutoMapperMappingsAttribute>(false) != null)

builder.RegisterModule<AutoMapperModule>();


this.Container = builder.Build();




Do I need to create a new module specific for my Unit tests or is there another way for this?



AutoMapperTest



[RequiresAutoMapperMappings]
[TestFixture]
public class AutoMapperTests : ApplicationTestBase

[Test]
public void Assert_Valid_Mappings()

Mapper.AssertConfigurationIsValid();




UPDATE



Like Cyril mentioned: Why do you need Ioc in your unit tests? I went searching and indeed you don't have to use the Ioc in your tests. So I ditched the Ioc and initialized my mapper configuration byy doing:



 Mapper.Initialize(configuration => 

var asm = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.StartsWith("ProjectWebService."));

configuration.AddProfiles(asm);
);









share|improve this question
























  • What are you testing ? why do you need IoC in your test ? See stackoverflow.com/questions/1465849/using-ioc-for-unit-testing

    – Cyril Durand
    Mar 8 at 14:36











  • See my update, I have create a test to check if my AutoMapper configuration is valid. Therefore I need to register my AutoMapper profiles and configuration, which is done in the AutoMapper Module.

    – Mivaweb
    Mar 8 at 19:27













0












0








0








Working on a project in ASP.NET Web API 2 which has Autofac as my IoC container. This project is hosted on IIS and in my Autofac module I use the following method to scan for assemblies:



var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


Why?



https://docs.autofac.org/en/latest/register/scanning.html#iis-hosted-web-applications



But now we are making Unit Tests using NUnit, during my setup I register my module which uses this method. Now I receive the following exception when running my tests:



System.InvalidOperationException: 'This method cannot be called during the application's pre-start initialization phase.'


I understand why I have this exception but I don't have a clue how to make my code work in tests and for deployment environments.



Setup method of NUnit:



[TestFixture]
public abstract class ApplicationTestBase

[SetUp]
public override void Init()

var builder = new ContainerBuilder();

// If the class requires auto mapper mapping, initialize them
// We do this in order not to init them for every test => optimalisation!
if (GetType().GetCustomAttributes<RequiresAutoMapperMappingsAttribute>(false) != null)

builder.RegisterModule<AutoMapperModule>();


this.Container = builder.Build();




Do I need to create a new module specific for my Unit tests or is there another way for this?



AutoMapperTest



[RequiresAutoMapperMappings]
[TestFixture]
public class AutoMapperTests : ApplicationTestBase

[Test]
public void Assert_Valid_Mappings()

Mapper.AssertConfigurationIsValid();




UPDATE



Like Cyril mentioned: Why do you need Ioc in your unit tests? I went searching and indeed you don't have to use the Ioc in your tests. So I ditched the Ioc and initialized my mapper configuration byy doing:



 Mapper.Initialize(configuration => 

var asm = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.StartsWith("ProjectWebService."));

configuration.AddProfiles(asm);
);









share|improve this question
















Working on a project in ASP.NET Web API 2 which has Autofac as my IoC container. This project is hosted on IIS and in my Autofac module I use the following method to scan for assemblies:



var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


Why?



https://docs.autofac.org/en/latest/register/scanning.html#iis-hosted-web-applications



But now we are making Unit Tests using NUnit, during my setup I register my module which uses this method. Now I receive the following exception when running my tests:



System.InvalidOperationException: 'This method cannot be called during the application's pre-start initialization phase.'


I understand why I have this exception but I don't have a clue how to make my code work in tests and for deployment environments.



Setup method of NUnit:



[TestFixture]
public abstract class ApplicationTestBase

[SetUp]
public override void Init()

var builder = new ContainerBuilder();

// If the class requires auto mapper mapping, initialize them
// We do this in order not to init them for every test => optimalisation!
if (GetType().GetCustomAttributes<RequiresAutoMapperMappingsAttribute>(false) != null)

builder.RegisterModule<AutoMapperModule>();


this.Container = builder.Build();




Do I need to create a new module specific for my Unit tests or is there another way for this?



AutoMapperTest



[RequiresAutoMapperMappings]
[TestFixture]
public class AutoMapperTests : ApplicationTestBase

[Test]
public void Assert_Valid_Mappings()

Mapper.AssertConfigurationIsValid();




UPDATE



Like Cyril mentioned: Why do you need Ioc in your unit tests? I went searching and indeed you don't have to use the Ioc in your tests. So I ditched the Ioc and initialized my mapper configuration byy doing:



 Mapper.Initialize(configuration => 

var asm = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.StartsWith("ProjectWebService."));

configuration.AddProfiles(asm);
);






unit-testing asp.net-web-api nunit autofac






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 11 at 15:33







Mivaweb

















asked Mar 8 at 12:25









MivawebMivaweb

4,09631541




4,09631541












  • What are you testing ? why do you need IoC in your test ? See stackoverflow.com/questions/1465849/using-ioc-for-unit-testing

    – Cyril Durand
    Mar 8 at 14:36











  • See my update, I have create a test to check if my AutoMapper configuration is valid. Therefore I need to register my AutoMapper profiles and configuration, which is done in the AutoMapper Module.

    – Mivaweb
    Mar 8 at 19:27

















  • What are you testing ? why do you need IoC in your test ? See stackoverflow.com/questions/1465849/using-ioc-for-unit-testing

    – Cyril Durand
    Mar 8 at 14:36











  • See my update, I have create a test to check if my AutoMapper configuration is valid. Therefore I need to register my AutoMapper profiles and configuration, which is done in the AutoMapper Module.

    – Mivaweb
    Mar 8 at 19:27
















What are you testing ? why do you need IoC in your test ? See stackoverflow.com/questions/1465849/using-ioc-for-unit-testing

– Cyril Durand
Mar 8 at 14:36





What are you testing ? why do you need IoC in your test ? See stackoverflow.com/questions/1465849/using-ioc-for-unit-testing

– Cyril Durand
Mar 8 at 14:36













See my update, I have create a test to check if my AutoMapper configuration is valid. Therefore I need to register my AutoMapper profiles and configuration, which is done in the AutoMapper Module.

– Mivaweb
Mar 8 at 19:27





See my update, I have create a test to check if my AutoMapper configuration is valid. Therefore I need to register my AutoMapper profiles and configuration, which is done in the AutoMapper Module.

– Mivaweb
Mar 8 at 19:27












1 Answer
1






active

oldest

votes


















0














I would recommend separating the "how to load assemblies" logic from the "do assembly scanning and register modules logic."



Right now I'm guessing you have something like this all in one method.



public IContainer BuildContainer()

var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(asm);
var container = builder.Build();



Not exactly that, but something similar - the loading of assemblies is inlined and directly used.



Separate that so you can swap that logic in for testing. For example, consider allowing a parameter to be optionally passed so you can override the logic in test.



public IContainer BuildContainer(Func<IEnumerable<Assembly>> assemblyLoader = null)

IEnumerable<Assembly> asm = null;
if (assemblyLoader != null)

asm = assemblyLoader();

else

asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(asm);
var container = builder.Build();



Your default logic will work the way you want, but then in testing you can swap in something else.



var container = BuildContainer(() => AppDomain.GetAssemblies());


There are lots of ways you can do that swap-in. It could be anything from a static property you can set somewhere to a virtual method you can override somewhere. The point is, by separating the assembly loading logic you can get the test-time behavior to work but still use the registration behavior you're after.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063215%2fasp-net-web-api-unit-test-autofac-module-with-buildmanager-getreferencedassembli%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I would recommend separating the "how to load assemblies" logic from the "do assembly scanning and register modules logic."



    Right now I'm guessing you have something like this all in one method.



    public IContainer BuildContainer()

    var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
    var builder = new ContainerBuilder();
    builder.RegisterAssemblyTypes(asm);
    var container = builder.Build();



    Not exactly that, but something similar - the loading of assemblies is inlined and directly used.



    Separate that so you can swap that logic in for testing. For example, consider allowing a parameter to be optionally passed so you can override the logic in test.



    public IContainer BuildContainer(Func<IEnumerable<Assembly>> assemblyLoader = null)

    IEnumerable<Assembly> asm = null;
    if (assemblyLoader != null)

    asm = assemblyLoader();

    else

    asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


    var builder = new ContainerBuilder();
    builder.RegisterAssemblyTypes(asm);
    var container = builder.Build();



    Your default logic will work the way you want, but then in testing you can swap in something else.



    var container = BuildContainer(() => AppDomain.GetAssemblies());


    There are lots of ways you can do that swap-in. It could be anything from a static property you can set somewhere to a virtual method you can override somewhere. The point is, by separating the assembly loading logic you can get the test-time behavior to work but still use the registration behavior you're after.






    share|improve this answer



























      0














      I would recommend separating the "how to load assemblies" logic from the "do assembly scanning and register modules logic."



      Right now I'm guessing you have something like this all in one method.



      public IContainer BuildContainer()

      var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
      var builder = new ContainerBuilder();
      builder.RegisterAssemblyTypes(asm);
      var container = builder.Build();



      Not exactly that, but something similar - the loading of assemblies is inlined and directly used.



      Separate that so you can swap that logic in for testing. For example, consider allowing a parameter to be optionally passed so you can override the logic in test.



      public IContainer BuildContainer(Func<IEnumerable<Assembly>> assemblyLoader = null)

      IEnumerable<Assembly> asm = null;
      if (assemblyLoader != null)

      asm = assemblyLoader();

      else

      asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


      var builder = new ContainerBuilder();
      builder.RegisterAssemblyTypes(asm);
      var container = builder.Build();



      Your default logic will work the way you want, but then in testing you can swap in something else.



      var container = BuildContainer(() => AppDomain.GetAssemblies());


      There are lots of ways you can do that swap-in. It could be anything from a static property you can set somewhere to a virtual method you can override somewhere. The point is, by separating the assembly loading logic you can get the test-time behavior to work but still use the registration behavior you're after.






      share|improve this answer

























        0












        0








        0







        I would recommend separating the "how to load assemblies" logic from the "do assembly scanning and register modules logic."



        Right now I'm guessing you have something like this all in one method.



        public IContainer BuildContainer()

        var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(asm);
        var container = builder.Build();



        Not exactly that, but something similar - the loading of assemblies is inlined and directly used.



        Separate that so you can swap that logic in for testing. For example, consider allowing a parameter to be optionally passed so you can override the logic in test.



        public IContainer BuildContainer(Func<IEnumerable<Assembly>> assemblyLoader = null)

        IEnumerable<Assembly> asm = null;
        if (assemblyLoader != null)

        asm = assemblyLoader();

        else

        asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(asm);
        var container = builder.Build();



        Your default logic will work the way you want, but then in testing you can swap in something else.



        var container = BuildContainer(() => AppDomain.GetAssemblies());


        There are lots of ways you can do that swap-in. It could be anything from a static property you can set somewhere to a virtual method you can override somewhere. The point is, by separating the assembly loading logic you can get the test-time behavior to work but still use the registration behavior you're after.






        share|improve this answer













        I would recommend separating the "how to load assemblies" logic from the "do assembly scanning and register modules logic."



        Right now I'm guessing you have something like this all in one method.



        public IContainer BuildContainer()

        var asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(asm);
        var container = builder.Build();



        Not exactly that, but something similar - the loading of assemblies is inlined and directly used.



        Separate that so you can swap that logic in for testing. For example, consider allowing a parameter to be optionally passed so you can override the logic in test.



        public IContainer BuildContainer(Func<IEnumerable<Assembly>> assemblyLoader = null)

        IEnumerable<Assembly> asm = null;
        if (assemblyLoader != null)

        asm = assemblyLoader();

        else

        asm = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();


        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(asm);
        var container = builder.Build();



        Your default logic will work the way you want, but then in testing you can swap in something else.



        var container = BuildContainer(() => AppDomain.GetAssemblies());


        There are lots of ways you can do that swap-in. It could be anything from a static property you can set somewhere to a virtual method you can override somewhere. The point is, by separating the assembly loading logic you can get the test-time behavior to work but still use the registration behavior you're after.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 11 at 15:13









        Travis IlligTravis Illig

        16.2k14471




        16.2k14471





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063215%2fasp-net-web-api-unit-test-autofac-module-with-buildmanager-getreferencedassembli%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко