w0051977
w0051977

Reputation: 15817

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.

Upvotes: 0

Views: 244

Answers (1)

Jan Muncinsky
Jan Muncinsky

Reputation: 4408

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>())

Upvotes: 1

Related Questions