简体   繁体   中英

Is it considered bad practice to create instances using the New keyword inside a library when using an IOC Container?

Please see the code below:

public class EnquiryFactory : IEnquiryFactory
    {
        public Enquiry Create(string firstName,string surname)
        {
            return new Enquiry(firstName,surname);
        }
    }

The Castle Windsor configuration looks like this:

container.Register(Castle.MicroKernel.Registration.Component.For<IEnquiryFactory>().ImplementedBy<EnquiryFactory>());

Is it considered bad practice to create instances using the New keyword inside a library when using an IOC Container? Should I be generating replacing this:

return new Enquiry(firstName,surname);

to something like this:

return container.resolve<Enquiry>(firstName,surname);

I have looked into the AsFactory facility: https://github.com/castleproject/Windsor/blob/master/docs/typed-factory-facility-interface-based.md , however I believe this is only used to create dependencies after an object is created.

As blins already commented it depends whether it's an issue that your application is coupled to Enquiry class. In your case it seems that Enquiry is just a DTO object with no behaviour, so in this case it wouldn't cause any trouble. But anyway as creating of Enquiry is already abstracted behind factory, you are always able to bring new implementations. Just like:

public class ExtendedEnquiryFactory : IEnquiryFactory
{
    public Enquiry Create(string firstName,string surname)
    {
        return new ExtendedEnquiry(firstName,surname);
    }
}

public class ExtendedEnquiry : Enquiry
{
}

And register your new factory instead the old one:

container.Register(Component.For<IEnquiryFactory>().ImplementedBy<ExtendedEnquiryFactory>())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM